---
title: "flatMap(_:)"
framework: swift
role: symbol
role_heading: Instance Method
path: "swift/optional/flatmap(_:)"
---

# flatMap(_:)

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

## Declaration

```swift
func flatMap<E, U>(_ transform: (Wrapped) throws(E) -> U?) throws(E) -> U? where E : Error, U : ~Copyable
```

## Parameters

- `transform`: A closure that takes the unwrapped value of the instance.

## Return Value

Return Value The result of the given closure. If this instance is nil, returns nil.

## Discussion

Discussion Use the flatMap method with a closure that returns an optional value. This example performs an arithmetic operation with an optional result on an optional integer. let possibleNumber: Int? = Int("42") let nonOverflowingSquare = possibleNumber.flatMap { x -> Int? in     let (result, overflowed) = x.multipliedReportingOverflow(by: x)     return overflowed ? nil : result } print(nonOverflowingSquare) // Prints "Optional(1764)"

## See Also

### Transforming an Optional Value

- [map(_:)](swift/optional/map(_:).md)
