Swift — Optional
Swift language introduced us to a new concept called?Optional. If you’re new to Swift the concept might seem unfamiliar or not intuitive at first, but?Optional?has its strengths and we’re here to explain them.
What is Optional?
The correct definition for?Optional ,?it’s an?Enum?with 2 cases, those 2 cases are:
Where none means the the value is empty — nil, and some means the value is actually containing something.
voilà — that’s the surprise hiding under this weird new thing we got called?Optional.
To be more clear, an?Optional?is a wrapper around the value, this wrapper can be one of two, either empty?(.None), or has something inside?(.Some(Wrapped)).
Let’s say the developer assign a new value to an?Optional?the basic constructor will be called, this constructor creates a new?Enum?with the value the developer assigned set into the?.Some?case.
On the other hand if the developer assigned a nil value to an?Optional,?the constructor will create an?Enum?with?.None?case. In the screenshot above we can see that?Optional?conforms the?ExpressibleByNilLiteral?Protocol, and that’s why it allows us to set a nil value into an?Optional.
Unwrapping
So, now that we understand what?Optional?is, how do we use it?
There are few ways to use an?Optional?value.
Unconditional unwrapping
Unconditional unwrapping can be achieved be using the character ‘!’. by using unconditional unwrapping we’re saying: “yes, I'm 100% sure there’s a value in that?Optional?and I want to use it”, example:
领英推荐
Optional unwrapping
Another way to unwrap an?Optional?value is to make a check before using the actual value if it’s there or not, example:
Swift 3.0 introduced us to Optional unwrapping which is basically the same as the snippet above, just a much better looking syntax, example:
The code snippet above takes the need to use the ‘!’ mark in order to unwrap the?Optional, because the acutal value is inside?unwrappedString?,?unwrappedString?is not an?Optional?but an actual string.
Guard
guard?statement was introduced in Swift 2.0, guard let’s you unwrap the Optional, but if it does not exist it forces you to execute a different code, meaning that the code beyond this point cannot run without this?Optional, example:
Conclusion
Swift introduced us to a new way of using values, the?Optional?which is a powerful object. Developers might get confused since it’s really easy to overlook?Optional?by using unconditional unwrapping, but when using?Optional?the right way it makes the code safe, easy to maintain and readable.
This is a brief explanation regarding?Optional?in Swift, further reading you can find?here