---
title: "compactMap(_:)"
framework: combine
role: symbol
role_heading: Instance Method
path: "combine/publisher/compactmap(_:)"
---

# compactMap(_:)

Calls a closure with each received element and publishes any returned optional that has a value.

## Declaration

```swift
func compactMap<T>(_ transform: @escaping (Self.Output) -> T?) -> Publishers.CompactMap<Self, T>
```

## Parameters

- `transform`: A closure that receives a value and returns an optional value.

## Return Value

Return Value Any non-nil optional results of the calling the supplied closure.

## Discussion

Discussion Combine’s compactMap(_:) operator performs a function similar to that of compactMap(_:) in the Swift standard library: the compactMap(_:) operator in Combine removes nil elements in a publisher’s stream and republishes non-nil elements to the downstream subscriber. The example below uses a range of numbers as the source for a collection based publisher. The compactMap(_:) operator consumes each element from the numbers publisher attempting to access the dictionary using the element as the key. If the example’s dictionary returns a nil, due to a non-existent key, compactMap(_:) filters out the nil (missing) elements. let numbers = (0...5) let romanNumeralDict: [Int : String] =     [1: "I", 2: "II", 3: "III", 5: "V"]

cancellable = numbers.publisher     .compactMap { romanNumeralDict[$0] }     .sink { print("\($0)", terminator: " ") }

// Prints: "I II III V"

## See Also

### Filtering elements

- [filter(_:)](combine/publisher/filter(_:).md)
- [tryFilter(_:)](combine/publisher/tryfilter(_:).md)
- [tryCompactMap(_:)](combine/publisher/trycompactmap(_:).md)
- [removeDuplicates()](combine/publisher/removeduplicates().md)
- [removeDuplicates(by:)](combine/publisher/removeduplicates(by:).md)
- [tryRemoveDuplicates(by:)](combine/publisher/tryremoveduplicates(by:).md)
- [replaceEmpty(with:)](combine/publisher/replaceempty(with:).md)
- [replaceError(with:)](combine/publisher/replaceerror(with:).md)
