Upgrade to Pro — share decks privately, control downloads, hide ads and more …

How to use Dictionary.compactMapValues

d_date
October 09, 2018

How to use Dictionary.compactMapValues

potatotips #55

d_date

October 09, 2018
Tweet

More Decks by d_date

Other Decks in Programming

Transcript

  1. 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. let d1 = ["a": "1", "b": "2", "c": nil] d1.filter({

    $0.value != nil}).mapValues({ $0! }) // ["b": "2", "a": "1"]
  3. var object = { 'a': 1, 'b': null, 'c': 3

    }; _.omitBy(object, _.isNil); // => { 'a': 1, 'c': 3 } DG@PNJU#Z
  4. 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. • compactMapValues is available in Swift 5 • compactMapValues can

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