Junior — Middle
How can `Optional` be used in Swift for safe handling of missing or undefined values?
sobes.tech AI
Answer from AI
In Swift, Optional is used to safely represent a value that may be absent (i.e., be nil). This helps avoid errors related to accessing non-existent values.
Example of using Optional:
var name: String? = "Ivan"
// Safe extraction of value through optional binding
if let unwrappedName = name {
print("Name: \(unwrappedName)")
} else {
print("Name is missing")
}
// Assigning nil
name = nil
Here, name can contain a string or nil. Using the if let construct allows safely obtaining the value if it exists and handling the case when the value is absent.