optional binding

if let, while let, guard let ็š„่ชžๆณ•็ตฑ็จฑ็‚บ "optional binding"ใ€‚

// โญ๏ธ if let/var
if let x = x { ... }
if var x = x { ... }    // `x` is mutable
if let x { ... }        // โญ๏ธ Swift 5.7: `= x` omitted

// โญ๏ธ guard let
guard let x = x else { ... }    // early exit

// โญ๏ธ while let
while let x = x { ... }

// โญ๏ธ multiple optional bindings & boolean conditions
if 
    let a = Int("4"),     // optional binding
    let b = Int("42"),    // optional binding
    a < b && b < 100      // boolean condition
{ ... }

// while let
while 
    let cat = cats[i], 
    cat.vaccinated 
{ ... }

Last updated