Swiftly

Swift 5.1 references for busy coders

Nil-coalescing operator (??)

The nil-coalescing operator is a shorthand alternative to if let-else.

Example if let-else

func greet(name: String?) {
  if let unwrappedName = name {
    print("Hello \(unwrappedName)!")
  } else {
    print("Hello guest!")
  }  
}
greet(name: "Asma") // Hello Asma!
greet(name: nil) // Hello guest!

Nil-coalescing equivalent

func greet(name: String?) {
  let unwrappedName = name ?? "guest"
  print("Hello \(unwrappedName)!")
}
greet(name: "Asma") // Hello Asma!
greet(name: nil) // Hello guest!