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

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. How to use Dictionary.compactMapValues potatotips #55 Daiki Matsudate / @d_date

  2. Daiki Matsudate @d_date

  3. https://peaks.cc/iOS_architecture

  4. IUUQTZBLJSJOHPCPPUIQNJUFNT

  5. Dictionary .compactMapValues

  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
  7. Use Cases

  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
  15. • Daiki Matsudate / @d_date Available in Swift 5

  16. Make our Swift better 09/05/2018 try! Swift NYC Daiki Matsudate

    / @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