Optional Binding
Optional binding is safely peeking inside the optional box and only using what's there if something actually is.
In this page:
Syntax
if let unwrapped = optionalValue {
// use unwrapped
} else {
// optionalValue was nil
}
if let a = optionalA, let b = optionalB { }
Basic if let Binding
if let attempts to unwrap an optional, running its block only when a value is actually present, with that value bound to a new constant.
Example: Basic if let Binding
// Declare a constant `possibleName` (a `String?`), set to `"Taylor"`
let possibleName: String? = "Taylor"
// If `possibleName` has a value, bind it to `name`
if let name = possibleName {
// Print "Hello, \(name)!" to the console
print("Hello, \(name)!")
// Otherwise, run this branch
} else {
// Print "No name provided" to the console
print("No name provided")
}
Login to try C/C++/Java/PHP code in the editor
Binding Multiple Optionals at Once
Several optionals can be unwrapped together in a single if let, separated by commas -- the block only runs if all of them have values.
Example: Binding Multiple Optionals at Once
// Declare a constant `firstName` (a `String?`), set to `"Ada"`
let firstName: String? = "Ada"
// Declare a constant `lastName` (a `String?`), set to `"Lovelace"`
let lastName: String? = "Lovelace"
// If `firstName, let last = lastName` has a value, bind it to `first`
if let first = firstName, let last = lastName {
// Print "Full name: \(first) \(last)" to the console
print("Full name: \(first) \(last)")
}
Login to try C/C++/Java/PHP code in the editor
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
Common Mistakes
- Using
if let value = valueand forgetting the boundvalueis only usable inside thatifblock's scope. - Nesting many separate
if letstatements when they can be combined into a singleif let a = a, let b = bstatement. - Shadowing the optional's name is fine and idiomatic in modern Swift, but forgetting that the new binding is a completely separate constant from the original optional.
Chapter Summary
if let name = optionalValuesafely unwraps and binds the value only if it exists.- The bound constant is only available inside the
ifblock's scope. - Multiple optionals can be unwrapped in one
if letstatement, separated by commas. - Optional binding avoids crashes since the block simply doesn't run if the value is
nil.
🔒
Chapter Quiz — Complete all 8 topics to unlock
0/8 topics done
Complete these topics first: