Swift & Concurrency (50 Qs)•Part 1: Core Language, Memory & Value Types (1 - 10)
What are Optionals and how do you safely unwrap them in Swift?
junior LevelswiftCore Language
In Simple Words:
An Optional represents a variable that can either hold a wrapped value or nil:
- Optional Binding (
if let/guard let): Safely unwraps the value (preferred standard). - Nil-Coalescing Operator (
??): Provides a fallback default value (let name = inputName ?? "Guest"). - Optional Chaining (
user?.address?.city): Gracefully fails tonilif any link in the chain isnil. - Forced Unwrapping (
!): Assumes value exists; fatal crash at runtime if value isnil! Avoid in production.