What are Optionals in swift ?

from apple docs
//: Playground - noun: a place where people can playimport UIKitvar numberOfCrashes : Int?
//: Playground — noun: a place where people can playimport UIKitvar numberOfCrashes : Int?numberOfCrashes = 3print(numberOfCrashes!)
//: Playground — noun: a place where people can playimport UIKitvar numberOfCrashes : Int?if numberOfCrashes != nil {print(numberOfCrashes!)}
//: Playground — noun: a place where people can playimport UIKitvar numberOfCrashes : Int?if let crashCount = numberOfCrashes {print(crashCount) // same as print(numberOfCrashes!)}

Question: Well… wait..!! can we use if-var for optional binding???

The answer is YES!!. But in most cases, it will be useless as the scope of the variable will be inside the if block only.

var surveyAnswer: String?// surveyAnswer is automatically set to nil

Unwrapping optionals

It can be done in a few ways:

— Forced unwrapping :

If you defined a variable as optional, then to get the value from this variable, you will have to unwrap it. This just means putting an exclamation mark at the end of the variable. This way of unwrapping by directly putting an exclamation mark at the end while accessing is called Forced unwrapping.

var myString:String?

myString = "Hello, Swift!"
let x = myString! // forced unwrapping Success!!!//_______________________________var myOtherString:String?

let x = myOtherString! // forced unwrapping Error. The value is not set.

— Implicit unwrapping :

An Implicitly Unwrapped Optional is an optional that doesn’t need to be unwrapped because it is done implicitly. These types of optionals are declared with an (!) instead of a (?). The only change is that this time the compiler will not yell at you. You can use it like a normal variable. Such optional variables will unwrap automatically and you do not need to use any further exclamation mark at the end of the variable to get the assigned value.This way of unwrapping is called implicit unwrapping .But keep in mind that the risk of crashing is high as you will have to manually keep track of the variable usage.

let someString: String! 
print(someString) // risk for crash is high.
import UIKitclass Vehicle {var model: String!}var cars = Vehicle()print(cars.model) // it may crash the app sometimes. the value is nil.
var myString:String!

myString = "Hello, Swift!"
let x = myString // x is an optional string with value "Hello, Swift!"//_______________________________var myOtherString:String!

let x = myOtherString // x will be an optional string. The value is not set (or nil).

Forced vs implicit unwrapping :

let possibleString: String? = "An optional string."let forcedString: String = possibleString! // requires an exclamation mark_______________let assumedString: String! = "An implicitly unwrapped optional string."let implicitString: String = assumedString // no need for an exclamation mark

—Optional Binding :

Use optional binding to find out whether an optional contains a value, and if so, to make that value available as a temporary constant or variable.

if let constantName = someOptional {
//statements using 'constantName'
} else {
// the value of someOptional is not set (or nil).
let possibleNumber = "123" // a string  nonOptional constantif let actualNumber = Int(possibleNumber) {print("\"\(possibleNumber)\" has an integer value of \(actualNumber)")} else {print("\"\(possibleNumber)\" could not be converted to an integer")}// Prints ""123" has an integer value of 123"
if let firstNumber = Int("4"), let secondNumber = Int("42"), firstNumber < secondNumber && secondNumber < 100 {print("\(firstNumber) < \(secondNumber) < 100")}// Prints "4 < 42 < 100"if let firstNumber = Int("4") {if let secondNumber = Int("42") {if firstNumber < secondNumber && secondNumber < 100 {print("\(firstNumber) < \(secondNumber) < 100")}}}// Prints "4 < 42 < 100"

Constants and variables created with optional binding in an if statement are available only within the body of the if statement. In contrast, the constants and variables created with a guard statement are available in the lines of code that follow the guard statement.

Digging deeper :

Let’s understand a little more about optionals. Let’s understand how optionals are used inside classes.

//: Playground — noun: a place where people can playimport UIKitclass Vehicle {var model: String?}
var car: Vehicle?
//: Playground — noun: a place where people can playimport UIKitclass Vehicle {var model: String?}var car: Vehicle?if let c = car {if let m = c.model {print(m)}}
if let c = car, let m = c.model {print(m)}
//: Playground — noun: a place where people can playimport UIKitclass Vechicle {var model: String?}var car: Vechicle?car = Vechicle() // created a new vehiclecar?.model = “Lamborgini”if let c = car, let m = c.model {
// only execute if car is valid and car has a valid model..
import UIKitclass Vehicle {var model: String?}var cars: [Vehicle]?cars = [Vehicle]()cars?.append(Vehicle()) // question mark in front of the dot is because it is an optional variable. if let carArray = cars, carArray.count > 0 {//execute only if cars array is valid and its count is greater than zero.

Optional chaining :

Optional chaining is a process for querying and calling properties, methods, and subscripts on an optional that might currently be nil. If the optional contains a value, the property, method, or subscript call succeeds; if the optional is nil, the property, method, or subscript call returns nil. Multiple queries can be chained together, and the entire chain fails gracefully if any link in the chain is nil.

let legs = House?.DiningRoom?.Chairs?.Legs?.first 
// just an example.. if chairs is nil, legs will be nil, if house is nil, chairs will obviously be nil and hence the legs..
import UIKitclass Human {var age: Intinit(age: Int) {self.age = age}}
class House {var human:Human?}
var houseObj = House()houseObj.human = Human(age: 10)
let ageOfHumanInHouse = houseObj.human?.age //ageOfHumanInHouse is optional Int

Its pretty simple.Lets assume that you saw a dream and you have a luxury house in your dream. The house in the dream is not real and you know that . So everything inside the house like a 100 inch curved LED tv , a lamborghini car in the garage , a luxury bed in the bedroom etc.. everything will be imaginary. It is just pure common sense.

Since ageOfHumanInHouse is optional Int (Int?) , we can use optional binding to unwrap it.

if let ageOfHumanInHouse = ageOfHumanInHouse {print(“\(ageOfHumanInHouse)”)}

Important: Optionals don’t interact with each other. We have to unwrap an optional in order to do that.

What is the nil coalescing operator?

source: Hackingwithswift

let name: String? = nil
let unwrappedName = name ?? "Anonymous"
let name: String? = nil
print("Hello, \(name ?? "Anonymous")!")

That’s it. !


If you enjoyed reading this post, please share and give some claps so others can find it 👏👏👏👏👏 !!!!

You can follow me on Medium for fresh articles. Also, connect with me on LinkedIn.



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store


iOS and tvOS developer, dreamer, photographer 🤨