Providing a default value for an Optional in Swift?
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.
Introduction
Swift's nil-coalescing operator ?? provides a default value when an optional is nil. The expression optionalValue ?? defaultValue unwraps the optional if it has a value, or returns the default if it is nil. This is the primary and most idiomatic way to provide fallback values for optionals in Swift.
The Nil-Coalescing Operator (??)
The ?? operator checks if the left side is nil. If not, it unwraps and returns the value. If nil, it returns the right side. The result type is non-optional.
Chaining Multiple Defaults
Swift evaluates left to right, using the first non-nil value. If all are nil, the final non-optional value is used.
With Dictionary Lookups
With Function Return Values
Default Value with Lazy Evaluation
The right side of ?? is evaluated lazily — it only executes if the optional is nil:
This is important for performance — expensive default computations are skipped when unnecessary.
Optional Binding (if let / guard let)
For more complex default logic, use optional binding:
Map and Default
Default Values in Function Parameters
Struct Default Values
Comparison with Other Unwrapping Methods
Common Pitfalls
- Force unwrapping instead of ??: Using
value!crashes onnil. Usevalue ?? defaultfor safe unwrapping with a fallback. Reserve!for cases whereniltruly indicates a programming error. - Expensive right-hand side: Although
??is lazy, developers sometimes forget this and avoid it unnecessarily. The default expression is only evaluated when the optional isnil. - Nested optionals:
let x: Int?? = nil; x ?? 0returnsOptional(0), not0. Double-optional wrapping requires careful handling — flatten withx.flatMap { $0 } ?? 0. - Confusing
??with?:value?.method()is optional chaining (propagates nil).value ?? defaultis nil-coalescing (provides fallback). They solve different problems but combine well:value?.count ?? 0. - Mutable default gotcha:
var items = optionalArray ?? []creates a new array if nil. Mutatingitemsdoes not affect the original optional. If you need to mutate the original, useif var.
Summary
- Use
??(nil-coalescing operator) to provide default values for optionals value ?? defaultreturns the unwrapped value or the default — result is non-optional- Chain multiple
??operators for cascading fallbacks - The right side is lazily evaluated — expensive defaults are only computed when needed
- Use
if let/guard letfor complex unwrapping logic beyond simple defaults - Prefer
??over force unwrapping (!) for safe, crash-free code
Related reading
- Provisioning profile doesn't include the application-identifier and keychain-access-groups entitlements
- Published property wrapper not working on subclass of ObservableObject
- Pull to refresh UITableView without UITableViewController
- Push Notifications in Android Platform
- Putting a LazyVStack or LazyHStack in a ScrollView causes stuttering
- R cannot be resolved - Android error
- R cannot be resolved - Android error
- R cannot be resolved to a variable?
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.