Optional

An Optional type allows to hold either a value or no value. Optionals typically are written by appending a ? to any type.

The nil literal indicates that variable does not have value. It is equivalent to the Optional.none.

let shortForm: Int? = Int("42")
let longForm: Optional<Int> = Int("42")

let noNumber1: Int? = nil
let noNumber2: Int? = Optional.none
print(noNumber2 == nil) // print true

There are variations of as operator for working with optionals:

  • as? - cast value to the specified type or return null if it is impossible
  • as! - cast value to the specified type or throw exception if it is impossible
let animal: Animal = Cat()
animal as? Dog	// evaluates to nil
animal as! Dog	// triggers a runtime error

The nil-coalescing operator ?? allows get default value when optional value is nil.

var userDefinedColorName: String?   // defaults to nil

var colorNameToUse = userDefinedColorName ?? defaultColorName
/* in other words
if userDefinedColorName == nil {
     colorNameToUse = defaultColorName
}else{
    colorNameToUse = userDefinedColorName
}*/

Finally, you can unwrap optional values with if let or guard let statements.

if let unwrapped1 = optionalExpression1(x), 
   let unwrapped2 = optionalExpression2 {
       
       a = unwrapped1 + 1 + unwrapped2
}

private func setupObserves() {
    guard let viewModel = viewModel else {
        return
    }

    viewModel.historyItems.observe { items in
        self.src = items
        self.historyTableView.reloadData()
    }
}