Test yourself under real exam conditions: 50 timed questions, 60 on the clock, pass mark 70%%. Instant score with a full review of everything you got wrong. Free — no account needed.
Exam details
An Optional in Swift represents a variable that can hold either a value or nil. It is declared using a ? after the type, e.g., var name: String?. Optionals enforce safe handling of the absence of a value at compile time.
You use optional binding with if let:if let unwrapped = optionalValue {
print(unwrapped)
}
This safely unwraps the optional and binds its value to a new constant within the block's scope.
Optional chaining uses ?. and returns nil if the optional is nil, failing gracefully.
Forced unwrapping uses ! and crashes at runtime if the optional is nil.
Example: person?.name vs person!.name
The nil-coalescing operator ?? provides a default value when an optional is nil.
Example: let name = optionalName ?? "Unknown"
If optionalName is nil, name is set to "Unknown".
An implicitly unwrapped optional is declared with ! instead of ?, e.g., var name: String!. It is automatically unwrapped when accessed, but will crash if it is nil. Used when a value is guaranteed to exist after initialization.