optionals

the optionals

let optional: String? = "unicorn" var optional2: Int? let optionals: [String?] = ["unicorn", nil, "dragon"] var optionals2: [Int]?

if let

if let value = optional {

multiple variables

if let value = optional, let value2 = optional2 {

boolean clause

if let value = optional, value.hasSuffix("saurus") {

guard

guard let value = optional else {   return }

while let

while let value = optional {

nil coalescing

let value = optional ?? "nil"

force unwrapping

let value = optional!

switch block

switch optional { case .some(let value):   print(value) case .none:   print("nil") }

failable initializers

init?(foo: String?) { guard let foo = foo else { return nil

map()

let value = optional.map(String.init(describing:))

flatMap()

let value = optional.flatMap(URL.init(string:))

compactMap()

let values = optionals.compactMap { $0 }

type casting

let value = optional as! String

optional chaining

let value = optional?.uppercased()

for loop

for element in optionals {   if let value = element {

for case let

for case let optional? in optionals {

for case .some

for case .some(let value) in optionals {

forEach

optionals2?.forEach { value in

errors to optional

converts a thrown error to optional

try? aThrowingCall() try! aThrowingCall()

optional blocks

call the block if not nil

var completion: (() -> Void)? completion?()

assignment

assigns if the optional has a value

optional2? = 2014

pattern matching

switch optional { case "unicorn"?:   print("Unicorn!") default:   print("Not Unicorn")

enums

enum Animal {   case pet(type: String?) }

switching with associated optionals

let enumValue = Animal.pet(type: optional) switch enumValue { case .pet(.some(let value)):   print("I am a \(value).") case .pet(.none):   print("I am unknown.") }

switching on optional enums

let enumValue2: Animal? = nil switch enumValue2 { case .pet?:   print("Pets") default:   print("No pets.") }

resources


Created by cak (+ friends) with syntax highlighting by Splash.

Contribute to this project on GitHub.