What are Optional Chaining , Optional Binding and Use of Guard key in Swift

Lakshmi K
3 min readMar 22, 2022

--

In so many interviews , interviewer will ask what is optional chaining and optional binding . It is a basic and common question from a fresher to experienced. So today we will see in details about this two with examples

Optional Chaining:

When we are calling any properties, methods and subscripts on optional values which may contain a nil value is called optional chaining. We won’t get any errors when we are querying optional value , we will get a nil value in return. We will use “?” for optional chaining. Let’s see an example .

struct User {

var name: String

var age : Int

var card : CreditCard? // reference to CreditCard

}

struct CreditCard {

var cardName : String

var number: String

var cvv : String

var address : Address? // reference to Address

}

struct Address {

var street : String

var area : String

var city : String?

var state : String?

var zipCode : String?

}

var iamUser : User? #1

iamUser = User(name: “MyName”, age: 26) #2

print(iamUser?.name) // #3 Optional chaining

var card : CreditCard?

card = CreditCard(cardName: “XYZBank”, number: “12345vdsfgfdsfgsd”, cvv: “432”)

iamUser?.card = card // #4

print(iamUser?.card?.cardName) // #5 Optional chaining

var myaddress : Address?

myaddress = Address(street: “street”, area: “area”)

card?.address = myaddress // #6

print(iamUser?.card?.address?.street) // #7 Optional chaining

#1 — creating a property of optional User

#2 — we are assigning values (initialising iamUser property) to iamUser property

#3 — this is optional chaining in practical , we are trying to call property (name) from an optional value (iamUser). Without #2 line if we try #3 line , it won’t give any errors it will just return nil value , you can try it.

#4 — before #4 line , we created CreditCard optional variable and assigned values to it, then in #4 line we are assigning this newly created card to card variable of iamUser

#5 — now if we want to know the card details of iamUser property , we need to use like this , first we will access iamUser then card variable then card details such as cardname , number and cvv ,etc. Here iamUser is optional and card is also an optional but we are still trying to get value from this 2 variables , this is called optional chaining . if any one of this variable contains nill then it returns nil value.

#6 — before #6 line , we created Address optional variable and assigned values to it , then in this line we assigned address to iamUser.card ‘s variable address variable.

#7 — iamUser?.card?.address?.street — here iamUser,card,address all these are optional values , we accessing properties of these optional values.

Optional Binding:

Instead of force unwrapping an optional value , first we will check if there is any value inside the optional value then we will use it , this process is called optional binding. We can do this two ways by using if statement and guard statement. Let’s see example below

var myOptional: String?

myOptional = “myNameXYZ” // without this assignement else will be executed in below if and else condition

if let temp = myOptional { // checking if value is there in myOptional then using it.

print(temp)

} else {

print(“myOptional was nil”) // if it nil handle the scenario here

}

With the above process we don’t need to use force unwrap to get the value of optional value , but here we have one problem the temp variable we can’t use outside of the if loop , we can only inside the if loop. So what’s the solution for this , we can use guard instead of if and make sure the variable is available outside of the if loop.

func greetings(myOptional : String?) {

guard let mytemp = myOptional else {

print(“myOptional value is empty”)

return

}

print(mytemp) // we can use mytemp any where inside greetings functions.

}

So these are detailed explanation about optional chaining and optional binding along with use of guard key with examples.

Please go through my other articles , thanks for reading. Happy Coding and Reading :)

--

--