An Optional is a type of its own that can handle the absence of a value. Optionals can contain nil values and there are multiple ways to unwrap them. In this article, we will understand why not to unwrap them forcefully and how to unwrap them safely.
Optionals
A type that represents either a wrapped value or nil, the absence of a value.
Some examples of optionals are:
/* Optional types either contain a value or nil. It can be defined as Optional<type>.
type? like Int? is syntatical sugar for Optional<type> like Int. */
struct Food {
var id: Int
var name: Optional<String>
var description: String?
}
Forced Unwrapping Optionals
Forced unwrapping extracts the value of the optional variable. Forced unwrapping assumes the value is definitely not-nil. Thus, it throws a fatal error if the variable is nil.
Optionals can be forced unwrapped by placing ! after the variable name.
var name: String? = "Pasta"
var desc: String? = nil
print(name!) //Prints Pasta
print(desc!) //Leads to runtime error since desc is set to nil
Implicitly Unwrapped Optionals
Implicitly unwrapped optionals are similar to optionals since they’re allowed to have nil value but they do not need to be checked before accessing. It’s called implicitly unwrapped since Swift force unwraps it every time. The drawback of this is same as forced unwrapping - if the value is nil when accessing, it leads to a fatal error.
Similar to optionals, optional binding and optional chaining can also be used for implicitly unwrapped optionals.
//Defining an implicitly unwrapped optional
var name: String!
//It will lead to runtime error if the value is nil when accessing
print(name)
Implicitly unwrapped optionals are mainly used for convenience when the value once initialised is never nil. Apple uses it for outlets. One has to be careful when using them since it is unsafe and can lead to runtime error if not handled carefully.
Optional Binding
To safely unwrap the value of an Optional , use one of the optional binding control structures, including if let and guard let. Optional binding conditionally binds the wrapped value of an Optional instance to a new variable.
var name: String?
if let name = name {
//Perform actions on the variable name
}
guard let name = name else {
//Handle case where name name is nil
}
//Perform actions on the variable name
What is the difference between guard let and if let?
guard let is designed to exit the current function, loop, or scope if the check fails so any values you unwrap using it will stay around after the check. Early exit from scope implies that the else block generally requires return or aborting the program.
On the other hand, values unwrapped using if let are accessible in the if block only. It doesn’t require a return statement.
Optional Chaining
Optional chaining is a method for querying and calling properties, methods or subscripts on an optional. If the value of the optional is nil, it fails gracefully. Optional chaining is specified by placing ? after the optional.
//Consider the example of struct food defined above
struct Meal {
var food: Food?
var calories: Int?
}
lunch = Meal()
if let foodID = lunch.food?.id {
...
} else {
...
}
//Values can also be set using optional chaining
lunch.food?.name = "Pizza"
//Optional chaining can be on multiple levels
struct Day {
var breakfast: Meal?
var lunch: Meal?
var dinner: Meal?
}
var today = Day()
if let dinnerName = today.dinner?.food?.name {
print(dinnerName)
}
Conclusion
Optionals are a powerful type in Swift allowing us to initialise variables with nil. Optionals can be unwrapped forcefully by using force unwrapping (unsafe). Implicitly unwrapped optionals use force unwrapping to access variable each time which may also lead to runtime error if its nil.
Optional binding is a safe way to unwrap an optional. Optional chaining gracefully accesses properties, methods and subscripts on an optional. Optional binding and chaining are suggested to use for utmost safety.
Wrapping up the article, you learned about the core topics of Optionals related to interview questions. You are now equipped with all knowledge required to ace the interview regarding these kind of questions. Till then,
Eat. Sleep. Swift Anytime. Repeat.
Oldest comments (0)