Optionals, Operators in Swift

We have no idea if we will have data or not until runtime, or when the application is running.

The nil-coalescing operator really shines here because it allows us to handle the case where someData could or may not have a value.

I think I have covered major concepts related to Optionals but we would see a lot of this in upcoming events, So you never know what Techshots you may get.

Moving on.

Let us talk about OperatorsOperatorsIf you know some math, you know the basic crux of Operators and Operands.

But for sake of recap, 2+3=5 2 and 3 are Operands and + is Operator.

And, you should know about the order of operations.

Parenthesis (from inside to outside)Exponents from left to rightMultiplication from left to rightDivision from left to rightAddition/ Subtraction from left to rightMath Operators/* Math Operators */var a = 10 + 20 //Additionvar b = 30 – 5 //Substractionvar c = 2 * 5 //Multiplicationvar d = 50/10 //Divisionnote about division, it is easy to divide numbers and end up with a float value (decimal value).

if you do not make the variable strongly typed you will end up, with an Integer value (6 / 5 = 1)var a: Float = 50 / 100 // a will be 0.

2Comparison Operators// Greater thanvar gt = 2 > 1 // gt is equal to true (2 is bigger)// Less thanvar lt = 2 < 1 // lt is equal to false (2 is not smaller)/* Equal to – we use double equal signs to determine equalitywe use a single equal sign for assignment */var eq = (2 == 2) // eq is equal to true (2 is equal to 2)// Greater than or equal tovar gtEq = (2 >= 2) // gtEq is equal to true (2 is equal to 2)//Less than or equal tovar ltEq = (2 <= 3) // ltEq is equal to trueUnary Operatorsvar notEq = (2 != 3) // notEq is true// Minus operator (there is a plus but it does not change anything)var minus = -(-100) // minus is 100// Logical Operators//And operator – this and that must be truevar andOp = (true && 4== 4) // andOp equals true// OR operator – this or that must be truevar orOp = (true || false).

// orOp equals true// Not operator – reverses the result of a boolean evaluationvar isLearning = !true // isLearning is falseRemainder/Modulo OperatorThe remainder operator (a % b) works out how many multiples of b will fit inside a and returns the value that is left over (known as the remainder).

You can fit two 4s inside 9, and the remainder is 1.

In Swift, this would be written as:var c = 9 % 4 // equals 1To determine the answer for a % b, the % operator calculates the following equation and returns remainder as its output:a = (b x some multiplier) + remainderwhere some multiplier is the largest number of multiples of b that will fit inside a.

Inserting 9 and 4 into this equation yields:9 = (4 x 2) + 1The same method is applied when calculating the remainder for a negative value of a .

Interesting right?var d = -9 % 4 // equals -1Inserting -9 and 4 into the equation yields:-9 = (4 x -2) + -1giving a remainder value of -1.

The sign of b is ignored for negative values of b.

This means that a % b and a % -b always give the same answer.

Compound Assignment OperatorIt combines assignment (=) with another operation.

Let’s seevar a : Int = 5a += 2 // a will be (5+2) =7a *= 3 // a will be (7*3) = 21a /= 21 // a will be 1 -> It is a shorthand for a = a/21Note: The compound assignment operators don’t return a value.

For example, you can’t write.

(You did think of that, didn’t you?)let b = a += 2.

Ternary Conditional OperatorThe ternary conditional operator is a special operator with three parts, which takes the form question ?.answer1 : answer2.

It’s a shortcut for evaluating one of two expressions based on whether question is true or false.

If question is true, it evaluates answer1 and returns its value; otherwise, it evaluates answer2 and returns its value.

var a : Int?var c : Stringif a != nil { c = "not nil value" } else { c = "nil value"}/* above can be written as */c = (a != nil)?."not nil value" : "nil value"Let’s see another example.

var a : Int?var c : Int = (a != nil) ? a! : 5Hang on for a second this use case is like unwrapping an optional if it has value else providing it a default value.

You must have seen this somewhere …You bet .

I have explained this.

Let me write to more shorthand format.

var a : Int?var c = a ?? 5Yupp, Scratch your head, That’s how Nil-Coalescing Operator came.

 :)Range OperatorsI will cover Range operators in Control Flow.

BonusOne topic which I missed in the previous article was Tuples.

What are Tuples?Tuples group multiple values into a single compound value.

The values within a tuple can be of any type and don’t have to be of the same type as each other.

Tuples enable you to create and pass around groupings of values.

You can use a tuple to return multiple values from a function as a single compound value.

let avengerData = ("Tony Stark", 48, "Iron-Man") /*Tuple is of type (String, Int, String)You can create tuples from any permutation of types, and they can contain as many different types as you like.

*/You can decompose a tuple’s contents into separate constants or variables, which you then access as usual:let (name, age, marvelCharacter) = avengerDataprint("(name) is (marvelCharacter)") // Tony Stark is Iron-Manor you can access the individual element values in a tuple using index numbers starting at zero:print("(avengerData.

0) is (avengerData.

1) years old")//prints Tony Stark is 48 years old No Endgame Spoiler above.

You can name the individual elements in a tuple when the tuple is defined:let avengerData = (name : "Tony Stark", age : 48)//and now i can access using these elementsprint("(avengerData.

name) is (avengerData.

age).

") //PRINTS Tony Stark is 48.

SummaryWell, part 2 is over.

You made it till here and slowly you will be having more fun, it next parts.

( Fingers crossed, I hope).

We learned about Optionals, Nil values, and Operators.

Some of the topics will be covered later, I assure you.

We are done for the day now.

Hopefully, You have understood concepts in the right way.

Thanks for reading this article.

Liked this article?You can give up to 50 claps: by long pressing the clap button.

if you enjoyed reading this article or learn something new, please tell your friends and share the love for this article.

What’s Next?In the next article, We will learn about Collection Types, Value Types, Reference Types.

For getting updates for interesting articles related to tech and programming to join TechShots.

Its a start to a long journey.

We will love the developers to be a part of this and publish blogs related to any tech they like.

You can also send us suggestions at techshotscommunity@gmail.

com.

Your feedback is very valuable.

TechshotsTechshots.

4 likes.

Educationwww.

facebook.

comReferenceshttps://developer.

apple.

com/documentation/swift/optionalhttps://docs.

swift.

org/swift-book/LanguageGuide/BasicOperators.

html.

. More details

Leave a Reply