Component - Optionals and unwrapping
This UI component shows how Swift uses optionals to hold values that might be missing. It demonstrates unwrapping an optional safely to display its content or a default message.
This UI component shows how Swift uses optionals to hold values that might be missing. It demonstrates unwrapping an optional safely to display its content or a default message.
View ├── VStack │ ├── Text (optionalValueLabel) │ └── Button (unwrapButton) └── Spacer
var name: String?var name: String? means name can be a String or nil.age: Int? using if let?if let to bind the Optional value if it exists.if let unwrappedAge = age. if age != nil { print(age) } checks nil but does not unwrap. if let age = age? { print(age) } has invalid syntax with age?. if age = nil { print(age) } wrongly assigns nil in condition.var score: Int? = 85
if let safeScore = score {
print("Score is \(safeScore)")
} else {
print("No score")
}score holds Optional Int with value 85.if let safeScore = score unwraps the value 85 successfully, so the print inside if runs.var text: String? = nil print(text!)
! on an Optional forces unwrap but crashes if nil.text is nil, so text! causes runtime crash.var input: String? = nil, which code safely prints the input or "No input" if nil using nil-coalescing??? provides a default value if Optional is nil.input ?? "No input" to print input or default. print(input!) force unwraps and crashes if nil. if let input = input { print(input) } else { print("No input") } uses if let but is longer. print(input ? "No input" : input) has invalid syntax.Pass the test and this pattern moves unknown