Throughout programming, we get into moments that variable will have no value assigned to it or it could contain a value. We call these variables Optionals in swift programming. Optional binding is a common practice of unwrapping nil values safely.
Let us discuss how the binding process works, by following steps.
- Step 1. We assign an optional value to a temporary variable or constant.
- Step 2. If this optional variable has a value, it is assigned to the temporary variable.
- Step 3. When the program executes, it will execute the first codes and unwrap the optional safely.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
var ourOptional: String? ourOptional = "Have some coffee" if let developer = ourOptional { print("We are having coffee") } else { print(programError) } var nilOptional: String? nilOptional = nil if let noCoffee = nilOptional { print("the optional have a value") } else { print("the optionals is nil") } |
Output: We are having coffee
Output: the optionals is nil
Crashing
Sometimes we force unwrap optionals by using an exclamation mark at the end of the variable. In this case, if the optionals have nil value, then it will force the program to crash.
For example:
1 2 |
var temp: String? = nil print (temp!) |
Which gives EXC_BAD_INSTRUCTION
To avoid these types of crashes, we use optional binding. To unwrap optionals, we can use the exclamation mark “!” or double question mark with a value, the variable will use this value when the optional is nil.
For example:
1 2 3 |
var greeting: String? print(greeting ?? "Hello World") |
Output: Hello World
Optional Unwrapping:
if -let statements :
Similarly, we can also use if let
statements to unbind the optionals. We can use this to find out whether an optional contains a value. If so, make that value available as a temporary constant or variable.
For example:
1 2 3 4 5 6 7 |
var greeting: String? greeting = "This is Swift" if let temp = greeting{ print(temp) } |
Output: This is Swift
Guard Statement :
Guard statements are simple and powerful. It checks for some conditions and if it evaluates to be false
, then the else
statement will execute which will exit the method. This is another way of writing if let statement.
For example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
func greeting(data: [String: String]) { guard let name = data["name"] else { return } print("Hello \(name)!") guard let location = data["location"] else { print("Location of \(name) is unknown.") return } print("\(name) lives in \(location)") } greeting(data: ["name": "John"]) // 1 greeting(data: ["name": "Jane", "location": "Cupertino"]) // 2 |
When 1
is executed, output:
Hello John!
Location of John is unknown.
When 2
is executed, output:
Hello Jane!
Jane lives in Cupertino
Conclusion
In this blog, we learned about OptionalBinding and safe methods to avoid crashes when unwrapping an optional variable. You can read more about OptionalBinding in swift from here.
You can read more of my blogs from this link.