---
title: "compactMapValues(_:)"
framework: swift
role: symbol
role_heading: Instance Method
path: "swift/dictionary/compactmapvalues(_:)"
---

# compactMapValues(_:)

Returns a new dictionary containing only the key-value pairs that have non-nil values as the result of transformation by the given closure.

## Declaration

```swift
func compactMapValues<T>(_ transform: (Value) throws -> T?) rethrows -> Dictionary<Key, T>
```

## Parameters

- `transform`: A closure that transforms a value. transform accepts each value of the dictionary as its parameter and returns an optional transformed value of the same or of a different type.

## Return Value

Return Value A dictionary containing the keys and non-nil transformed values of this dictionary.

## Discussion

Discussion Use this method to receive a dictionary with non-optional values when your transformation produces optional values. In this example, note the difference in the result of using mapValues and compactMapValues with a transformation that returns an optional Int value. let data = ["a": "1", "b": "three", "c": "///4///"]

let m: [String: Int?] = data.mapValues { str in Int(str) } // ["a": Optional(1), "b": nil, "c": nil]

let c: [String: Int] = data.compactMapValues { str in Int(str) } // ["a": 1] note: O(m + n), where n is the length of the original dictionary and m is the length of the resulting dictionary.

## See Also

### Transforming a Dictionary

- [mapValues(_:)](swift/dictionary/mapvalues(_:).md)
- [reduce(_:_:)](swift/dictionary/reduce(_:_:).md)
- [reduce(into:_:)](swift/dictionary/reduce(into:_:).md)
- [compactMap(_:)](swift/dictionary/compactmap(_:).md)
- [flatMap(_:)](swift/dictionary/flatmap(_:)-i3ly.md)
- [flatMap(_:)](swift/dictionary/flatmap(_:)-6chv9.md)
- [sorted(by:)](swift/dictionary/sorted(by:).md)
- [shuffled()](swift/dictionary/shuffled().md)
- [shuffled(using:)](swift/dictionary/shuffled(using:).md)
