Optionals, Operators in Swift

Yash Awasthi
TechShots
Published in
8 min readMay 17, 2019

In the previous article, we have talked about variables, constants, and types. (not all of them). In this article, we will majorly discuss optionals and operators.

What is Optionals?

One of the most difficult concepts of swift but hold my beer, I will try to explain it in simple terms. So let me ask you a question. “What is your middle name?”.

Most of you would say, huh? I don’t have a middle name, but few of you would say oh hang on, I have a middle name Like “Willhelm”. ( I am referring to Leonardo Willhelm Dicaprio) . Okay, so how would I handle this kind of scenario where someone has a middle name and someone doesn’t have it?

Clearly, we can say data can be absent here and in programmatical terms, we can say for some individuals MiddleName holds some value and for some it holds nothing.

Apple says about Optionals -

A type that represents either a wrapped value or nil, the absence of a value.

There are circumstances where we wish to accept data from consumers and also provide a chance for some of the data to be optionals, meaning they are not necessary but should be provided if available.

Now, what is this wrapped value or nil means?

Think of an optional as a kind of parcel. Before you open it (or “unwrap” in the language of optionals) you won’t know if it contains something or nothing. It is only an Optional value that can be set to nil .

/* Creating an Optional */
var middleName : String? //middleName consists value of nil
/*You can also specify the alternative writing:var middleName : String? = nil */middleName = "Willhelm" //middleName has some value nowprint("Middlename of this folk is \(middleName)")
//prints Optional("Willhelm")
/* Unwrapping an Optional */
print("Middlename of this folk is \(middleName!)") //prints Willhelm

So are you with me? I hope you are. We have instantiated a variable as an Optional. Now, there is a difference between String and String? .

Let’s see how.

var name : String
name = nil // error: nil cannot be assigned to type 'String'

So if you don’t define a variable as an Optional, you can not assign it to nil . If it is an Optional and you are unwrapping it by using !, it must contain some value at this point else your application will crash at runtime.

/* You can declare in this way also called as long form syntax */
var middleName : Optional<String>
print("middlename is \(middleName!)") //It will crash here

So how do you ensure that you don’t let your application crash?. There are following ways

  • Use if check
  • Use Optional Binding
  • Using the Nil-Coalescing Operator

Use if check

Since it was nil that was passed to the variable when we initialized middleName. we can use an if statement to check for nil before unwrapping it. We will discuss about if statements in detail later in this series.

var middleName : String?if middleName != nil {
print("middlename is \(middleName!)")
}

Above print statement will execute only when middleName have some value.

Use Optional Binding.

With optional binding, though we are still using if , Swift provides a way for us to use if let statement then automatically unwrap it for us like below.

var middleName : String?if let middleNameWithValue = middleName {
print("middlename is \(middleNameWithValue)")
}

we will talk about guard statements which can be used for optional binding and early return later in this series.

Using the Nil-Coalescing Operator

The nil-coalescing operator ?? is used to check if the value on the left-hand side is nil. If it is, we can set a default value on the right-hand side.

var someData : String?
let data: String = someData ?? "No data found"
/* it can also be used in chains */var name : String?
var lastName : String?
let individualData : String = name ?? lastName ?? "Not found"

Does someData have a value or not? What if we got this data from the web? 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 Operators

Operators

If 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.

  1. Parenthesis (from inside to outside)
  2. Exponents from left to right
  3. Multiplication from left to right
  4. Division from left to right
  5. Addition/ Subtraction from left to right

Math Operators

/* Math Operators */var a = 10 + 20 //Addition
var b = 30 - 5 //Substraction
var c = 2 * 5 //Multiplication
var d = 50/10 //Division

note 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.2

Comparison Operators

// Greater than
var gt = 2 > 1 // gt is equal to true (2 is bigger)
// Less than
var lt = 2 < 1 // lt is equal to false (2 is not smaller)
/* Equal to - we use double equal signs to determine equality
we 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 to
var gtEq = (2 >= 2) // gtEq is equal to true (2 is equal to 2)
//Less than or equal to
var ltEq = (2 <= 3) // ltEq is equal to true

Unary Operators

var 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 true
var andOp = (true && 4 == 4) // andOp equals true
// OR operator - this or that must be true
var orOp = (true || false). // orOp equals true
// Not operator - reverses the result of a boolean evaluation
var isLearning = !true // isLearning is false

Remainder/Modulo Operator

The 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 1

To determine the answer for a % b, the % operator calculates the following equation and returns remainder as its output:

a = (b x some multiplier) + remainder

where 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) + 1

The same method is applied when calculating the remainder for a negative value of a . Interesting right?

var d = -9 % 4 // equals -1

Inserting -9 and 4 into the equation yields:

-9 = (4 x -2) + -1

giving 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 Operator

It combines assignment (=) with another operation. Let’s see

var a : Int = 5
a += 2 // a will be (5+2) =7
a *= 3 // a will be (7*3) = 21
a /= 21 // a will be 1 -> It is a shorthand for a = a/21

Note: 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 Operator

The 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! : 5

Hang 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 ?? 5

Yupp, Scratch your head, That’s how Nil-Coalescing Operator came. :)

Range Operators

I will cover Range operators in Control Flow.

Bonus

One 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) = avengerData
print("\(name) is \(marvelCharacter)") // Tony Stark is Iron-Man

or 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 elements
print("\(avengerData.name) is \(avengerData.age).")
//PRINTS Tony Stark is 48.

Summary

Well, 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. I will ensure that some missing topics will be covered later. 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.

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.

References

  1. https://developer.apple.com/documentation/swift/optional
  2. https://docs.swift.org/swift-book/LanguageGuide/BasicOperators.html

--

--