Junior — Middle
What is the purpose of the Optional type in programming?
sobes.tech AI
Answer from AI
The Optional type in programming, for example in Swift, is used to denote a variable that can contain either a value of a certain type or be absent (nil). This helps explicitly handle the possibility of a missing value, reducing the likelihood of errors related to null or nil.
Example:
var name: String? = nil
name = "Ivan"
if let unwrappedName = name {
print("Name: \(unwrappedName)")
} else {
print("Name is missing")
}
Here, Optional allows safe checking for the presence of a value before using it.