Basics: Optionals
Let possibleNumber = "123"
let convertedNumber = Int(possibleNumber)
// convertedNumber is inferred to be of type "Int?", or "optional Int"
Use optionals in situations where a value may be absent.
Represents two possibilities: Either there is a value, and you can unwrap the optional to access that value, or there isn’t a value at all.
Nil
Var serverResponseCode: Int? = 404
// serverResponseCode contains an actual Int value of 404
serverResponseCode = nil
// serverResponseCode now contains no value
It’s the absence of a value of a certain type.
Additional information
If Statements and Forced Unwrapping
If convertedNumber != nil {
print("convertedNumber contains some integer value.")
}
// Prints "convertedNumber contains some integer value."
If convertedNumber != nil {
print("convertedNumber has an integer value of \(convertedNumber!).")
}
// Prints "convertedNumber has an integer value of 123."
Additional information
Optional Binding
Can be used with if and while statements to check for a value inside an optional, and to extract that value into a constant or variable, as part of a single action.
If let actualNumber = Int(possibleNumber) {
print("The string \"\(possibleNumber)\" has an integer value of \(actualNumber)")
} else {
print("The string \"\(possibleNumber)\" could not be converted to an integer")
}
// Prints "The string "123" has an integer value of 123"
You use optional binding to find out whether an optional contains a value, and if so, to make that value available as a temporary constant or variable.
Implicitly Unwrapped Optionals
Are useful when an optional’s value is confirmed to exist immediately after the optional is first defined and can definitely be assumed to exist at every point thereafter. .
Let possibleString: String? = "An optional string."
let forcedString: String = possibleString! // requires an exclamation mark
Let assumedString: String! = "An implicitly unwrapped optional string."
let implicitString: String = assumedString // no need for an exclamation mark
If assumedString != nil {
print(assumedString!)
}
// Prints "An implicitly unwrapped optional string."
If let definiteString = assumedString {
print(definiteString)
}
// Prints "An implicitly unwrapped optional string."
Optional will always have a value, after that value is first set.
Is a normal optional behind the scenes, but can also be used like a nonoptional value, without the need to unwrap the optional value each time it’s accessed.