d_date
October 09, 2018
4.8k

# How to use Dictionary.compactMapValues

potatotips #55

October 09, 2018

## Transcript

6. ### extension Dictionary { public func compactMapValues<T>(_ transform: (Value) throws ->

T?) rethrows -> [Key: T] { return try self.reduce(into: [Key: T](), { (result, x) in if let value = try transform(x.value) { result[x.key] = value } }) } } Available in Swift 5

8. ### let d1 = ["a": "1", "b": "2", "c": nil] d1.filter({

\$0.value != nil}).mapValues({ \$0! }) // ["b": "2", "a": "1"]
9. ### ["a": "1", "b": nil, "c": “3”].compactMapValues({ \$0 }) // ["a"

: 1, "c" : 3]
10. ### var object = { 'a': 1, 'b': null, 'c': 3

}; _.omitBy(object, _.isNil); // => { 'a': 1, 'c': 3 } DG@PNJU#Z
11. ### let d = ["a": "1", "b": "2", "c": "three"] d.mapValues(Int.init).filter({

\$0.value != nil}).mapValues({ \$0! })
12. ### extension Dictionary { public func compactMapValues<T>(_ transform: (Value) throws ->

T?) rethrows -> [Key: T] { return try self.reduce(into: [Key: T](), { (result, x) in if let value = try transform(x.value) { result[x.key] = value } }) } }
13. ### let d = ["a": "1", "b": "2", "c": "three"] d.compactMapValues(Int.init)

// ["b": 2, "a": 1]
14. None

/ @d_date
17. None
18. ### • compactMapValues is available in Swift 5 • compactMapValues can

transform and unwrap dictionary • Let’s try to contribute to Swift lang Recap
19. None