How to use Dictionary.compactMapValues

2594ac7ce91fd7d9a3ce71ca7cc2d0c0?s=47 d_date
October 09, 2018

How to use Dictionary.compactMapValues

potatotips #55

2594ac7ce91fd7d9a3ce71ca7cc2d0c0?s=128

d_date

October 09, 2018
Tweet

Transcript

  1. 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
  2. 8.

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

    $0.value != nil}).mapValues({ $0! }) // ["b": "2", "a": "1"]
  3. 10.

    var object = { 'a': 1, 'b': null, 'c': 3

    }; _.omitBy(object, _.isNil); // => { 'a': 1, 'c': 3 } DG@PNJU#Z
  4. 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 } }) } }
  5. 14.
  6. 17.
  7. 18.

    • compactMapValues is available in Swift 5 • compactMapValues can

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