Generic Instance Method

map(_:)

Evaluates the given closure when this Optional instance is not nil, passing the unwrapped value as a parameter.

Declaration

func map<U>(_ transform: (Wrapped) throws -> U) rethrows -> U?

Parameters

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 nonoptional 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"

See Also

Transforming an Optional Value

func flatMap<U>((Wrapped) -> U?) -> U?

Evaluates the given closure when this Optional instance is not nil, passing the unwrapped value as a parameter.