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
{ ... }
optional binding can be used with if
and while
statements to check for a value inside an optional.
if let
vs. guard let
if let
: bound variables are available only within the body of theif
statement.guard let: bound variables are available in the lines of code that follow the
guard
statement.
Swift โฉ The Basics โฉ Optionals โฉ Optional Binding
โญ๏ธ Swift 5.7 - new syntax for optional binding.
Last updated