As you begin to write code, you may discover that your code will sometimes run successfully and sometimes fail. One of the most prevalent causes of code failure is when it tries to use faulty or missing data. However, since Swift is a very safe language, it ensures that your codes will not fail in unexpected ways. Swift did this by introducing optionals.
With an optional, there are two possibilities: either there is a value, which you may obtain by unwrapping the optional, or there isn’t one at all. An optional serves as a container for a specific type of value. This container may or may not contain a value.
A question mark ?
is used to declare an optional. An optional variable is declared by appending a question mark to the end of the variable’s data-type declaration. For instance:
var name: String?
Use an optional when you want to be on the safe side. Declare the variable as an optional type if you are unsure whether or not it will have a value.
It is safer to declare this kind of variable as an optional to avoid surprises when coding.
An optional wraps a value up like a parcel, meaning that you cannot access the value of an optional like you access the value of a variable or constant. So, you would need to unwrap an optional value in order to use it.
You can perform unwrapping in the following ways:
In this shot, we’ll concentrate on the first three because they’re the most common.
Unwrapping is the process of checking the variable to ensure that the optional value is not nil. You can accomplish this with a simple if-else block (if
, if let
or guard let
), like this:
var name: String? //optional declarationif name != nil{print("Name is Not nil")}else{print("Nil")}//Output : Nil// The if let optional unwrappingif let somethingToUnwrap = name {print("\(somethingToUnwrap.count) letters in total")} else {print("Name is missing.")}// The guard let optional unwrappingfunc greet(_ name: String?) {guard let somethingToUnwrap = name else {print("Name is missing!")return}print("Hello there, \(somethingToUnwrap)!")}
The nil coalescing operator functions as a shorthand representation for the conventional if-else block.
If there is a value inside an optional, the nil coalescing operator unwraps it and returns it. If the optional was nil, and there was no value, a default value is used instead. In either case, the result will not be optional. Instead, it will either return the value from within the optional or the default value used as a backup.
var variableName: String?var message = variableName ?? "Default value"print(message) // Default valuevariableName = "This is a string"message = variableName ?? "Default String"print(message) // This is a string
Here, unwrapping is a bit different because you’re accessing an optional regardless of its value (nil or not nil), and forced unwrapping is quite contradictory. If a nil optional is unwrapped, an error message stating “Unexpectedly found nil while unwrapping an optional value.” is thrown, and your program will terminate or crash.
You should only use forced unwrapping in a pre-defined environment where you know the optional value will not be nil.
By using the exclamatory !
operator, you can forcefully unwrap an optional, as shown below:
var country: String?;print(country!) // Unexpectedly found nil while unwrapping an Optional value
Note that using forced unwrapping when you are not sure an optional contains a value can cause your code to fail. So, ensure that you have a value before using an exclamation mark to force unwrap an optional.
There you have it! Feel free to use optionals in your codes. Thanks for reading!