A concise, runnable playground demonstrating optional chaining in Swift.
Optional chaining is a process for querying and calling properties, methods, and subscripts on an optional that might currently be nil. If the optional contains a value, the call succeeds; if it is nil, the whole expression evaluates to nil instead of crashing.
This repository is a concise, runnable Swift playground learning example. It shows how the ? operator lets you safely reach into a chained call and gracefully unwrap the result.
- Using the optional-chaining operator (
?) after a call that returns an optional - Chaining
firstIndex(of:)on an array with.descriptionand.uppercased()in a single expression - How the entire expression short-circuits to
nilwhen the value is absent - Producing a safely unwrapped optional
Stringresult without force unwrapping
let optionalChainingArray = ["Ahmet", "Alex", "Marcus", "Marie", "Natalie", "Ayla", "Marcus"]
let object = optionalChainingArray.firstIndex(of: "Marcus")?.description.uppercased()git clone https://github.com/ahmetbostanciklioglu/OptionalChaining.git
cd OptionalChainingUnzip OptionalChaining.playground.zip, open OptionalChaining.playground in Xcode, and run it to see the results appear inline.
- Xcode 12 or later
- Swift 5
- iOS playground target
Ahmet BostancΔ±klΔ±oΔlu β @ahmetbostanciklioglu Β· ahmetbostancikli@gmail.com
β If this helped you, consider giving the repo a star!