Swift Optionals and Unwrapping

Aug 1, 2018 swift unwrapping optionals binding
Optionals is a Swift type. The key thing to remember is it can hold a value or no value. We append ? to any type to declare it as an optional

var beer: String? = “Atomic”

Optional definition

enum Optional {
case none
case some(T)

Under the hood we can see that an optional is simply just an enum type with two cases. None - with no value set and some - a value is set and it’s generic type.

Optional Binding

A safe method to unwrap a value from a constant or variable in a single action. It allows us to check the value and extract the value while directing the flow through a binary path - if else. This check is considered safe because we are not assuming a particular type of type or even a value. The entire statement can be nil and the runtime will continue as normal.

if let whatShallWeDrinkTonight = anUnknownBeer {
print(“Tonight’s drink is \(whatShalleWeDrinkTonight”)
else {
print(“we’re not drinking tonight :(“)

Forced unwrapping “!”

Forced unwrapping is considered lethal when dealing with unknown and uncertain types. It would be like closing your eyes and catching a heavy ball. There’s a chance this ball will crash into our face and we don’t want that at all. Despite how dangerous forced unwrapping can be, unless you’re absolutely certain this cannot happen then by all means use it. It is available for use but it is frowned upon.

// forced unwrapping
let b: String? = "Hi there"
var a = b!

Forced unwrapping definition
// under the hood forced unwrapping is a switch statement
switch b {
case .Some(let value): a = value
case .None: //raise an exception

It’s good practice to not even use these at all if you can avoid it as it’s probable we’ll run into errors. If you’re not sure on the type or if it has a value, be safe and use optional binding instead.

Implicitly unwrapped optionals

Nil coalescing
This allows us to define and assign a value if it returns nil as it’s default value. Rather than using multiple if statements, nil coalescing performs this task in one simple line. Even though a ternary operator would also offer the same one liner, this further shortens it. If you understand the syntax it’s very clear what’s happening but if you’re new try using the ternary operator first and then shortening it further with nil coalescing.

Ternary example

let myFavoriteBeer: String? = nil

let myCurrentFavBeer = myFavoriteBeer != nil ? myFavoriteBeer! : “If it had to be anything it’d be a nice cold Blue Moon”

Nil coalescing example

let myFavoriteBeer: String? = nil

let myCurrentFavBeer = myFavoriteBeer ?? “If it had to be anything it’d be a nice cold Blue Moon”

If you found the following info helpful, I'm happy to accept any donations of the following cryptocurrencies.

  • Bitcoin - 17DTiPExzP9StqveW428acEyB4mVMfKbiK
  • Ethereum - 0x87B8307FD20dc90cc05c94905Ec593134D32B6FF
  • Litecoin - LZMiz5U5sVq9doMLYE3gfLJrxCQDKuyCmU
  • Neo - AXv71WB38ajc1KUUEnxQKhynLLPc4BapVb