Junior — Middle
How is the storage of optional values implemented in programming?
sobes.tech AI
Answer from AI
In programming, optional values are used to denote variables that can either contain a value of a certain type or be absent (nil, null). In iOS (Swift), there is a type called Optional that wraps a value and indicates that it can be either a value or nil.
Example in Swift:
var name: String? = "Ivan"
name = nil // now the variable does not contain a value
if let unwrappedName = name {
print("Name: \(unwrappedName)")
} else {
print("Name is missing")
}
This approach allows safe handling of potential absence of a value, avoiding errors when accessing nil. Similar concepts are used in other languages: Optional in Kotlin, Nullable in C#, Maybe in Haskell, etc.