map(_:)
Evaluates the given closure when this Optional instance is not nil, passing the unwrapped value as a parameter.
Declaration
func map<E, U>(_ transform: (Wrapped) throws(E) -> U) throws(E) -> U? where E : Error, U : ~CopyableParameters
- transform:
A closure that takes the unwrapped value of the instance.
Return Value
The result of the given closure. If this instance is nil, returns nil.
Discussion
Use the map method with a closure that returns a non-optional value. This example performs an arithmetic operation on an optional integer.
let possibleNumber: Int? = Int("42")
let possibleSquare = possibleNumber.map { $0 * $0 }
print(possibleSquare)
// Prints "Optional(1764)"
let noNumber: Int? = nil
let noSquare = noNumber.map { $0 * $0 }
print(noSquare)
// Prints "nil"