Explain various ways to unwrap an optional in the Swift language


Declaring variables as optional is always recommended and should be the first choice of a developer. You should mark them as optional if they can be invalid (nil or another type).

Being developers, we consider it our responsibility to write safe and secure code. To make it possible, Swift provides us with many concepts, and optional is one of them.

The optional variable might contain a nil value, so we have to get its value safely. There are a couple of ways to unwrap the value of an optional variable. Let's learn about them.

First, we need to understand what is optional in Swift.

Optionals

When we receive a value from other sources like the backend server, this value might contain a valid value or nothing at the initial point. In that case, you use optionals that represent a variable with two possible situations − either a value or no value at all.

var possibleNumber = "450"
var convertedNumber = Int(possibleNumber)

In the above example, there is an input string that we are converting into an Int. However, this string might or might not be a valid integer number. In that case, once we convert this string into an integer using the Int() function, it will return an optional integer value. This means the output can be nil or a valid integer value.

Unwrap an Optional

Getting a value (valid or nil) from an optional variable is called unwrapping. To use the casted value from optional variables, we have to cast them safely.

Value can be obtained in many ways, but each method is used in a different situation.

  • Using force to unwrap

  • Using optional binding

  • Using optional chaining

  • Using the nil-coalescing operator

Using Forced Unwrapping (not recommended)

Example

In this method, you can access the value by adding an exclamation point (!) after the variable name. Like below −

var errorMessage: String? = "Invalid URL found"
print(errorMessage!)

Output

Invalid URL found

If you are sure that the optional variable contains a value, then you can use it (!), otherwise, the app will crash if the variable does not contain a value. Simply an exclamation point implies, "I know that this optional definitely has a value; please use it."

Example

There is a way to check first and use an exclamation point with optional variables like below:

var errorMessage: String? = "Invalid URL found"
if errorMessage != nil {
   print("error message is not nil: \(errorMessage!)")
}

Output

error message is not nil: Invalid URL found

Explanation

First, we declare an optional variable of type string. Next, we check that the variable is not equal to nil. If not nil, print the value of the variable. In this way, your app will not crash because you have already checked for it.

Optional Bindings (recommended)

To read the value of an optional variable, this is the recommended method. In this method, you check whether the variable has a value or not. If a value is found, you hold the value in a local constant or variable.

Optional binding can be used to conditionally execute code, control the execution of a loop, and create early exit paths from the current scope. Multiple optional bindings can be used in one statement, and optional binding can be used in combination with optional chaining to make code more compact.

Example

Let's see an example −

var errorMessage: String? = "Invalid URL found"
if let message = errorMessage {
   print("Error message: \(message)")
}

Output

Error message: Invalid URL found

Here, you are storing the value in a temporary constant 'message' and then using it. If errorMessage has no value or is nil, then the if condition will not be true. So, you can see this is a very safe method to unwrap a value from optional variables.

Using Optional Chaining

Example

While you are dealing with more than one optional variable at once, you might need to use multiple if-let statements. To avoid this mess, we can use optional chaining to unwrap the value.

struct College {
   let name: String
   var address: String?
}
struct Student {
   let name: String
   let grade: Int
   var college: College?
}
let martin: Student? = Student(name: "Martin", grade: 5)
// here, getting the address using optional chaining.
if let address = martin?.college?.address {
   print("address: \(address)")
} else {
   print("address not found")
}

Output

address not found

Using The Nil-Coalescing Operator

It is a very simple and short notation to avoid an if-else block statement. We can return a default value in case you found a nil value in an optional variable.

Example

In this, the unwrapped value is used in the case of a non-nil value. Otherwise, the default value is going to be used.

var name: String?
let nameString = name ?? "Default value"
print(nameString)

Output

Default value

Conclusion

To deal with optional, we can apply various ways to unwrap an optional. In the Swift language, each method can be used for a different purpose. It's always recommended to use a safe method to unwrap an optional to prevent unwanted crashes in the application.

Updated on: 21-Dec-2022

435 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements