4

I have a dictionary of type [String: [SomeObject]?] and I want to map it to another dictionary of the same type but in some cases remove elements from the inner array.

How to solve this issue? If it is possible to do with swift features only like map, filter, reduce and etc. without iterating and recreating a new dictionary manually?

Vyachaslav Gerchicov
  • 2,317
  • 3
  • 23
  • 49
  • 1
    In Swift 4, `Dictionary` has a [`mapValues(_:)`](https://developer.apple.com/documentation/swift/dictionary/2894692-mapvalues) method. – Possible duplicate of https://stackoverflow.com/questions/24116271/whats-the-cleanest-way-of-applying-map-to-a-dictionary-in-swift. – Martin R Dec 22 '17 at 10:04
  • @MartinR And? That question is about objects/values which have constant count. My question is about arrays which have varying count of inner elements – Vyachaslav Gerchicov Dec 22 '17 at 11:54

1 Answers1

4

let's say we have the following [String: [Int]]:

var dict = ["k1":[-1, -2, 1, 2]]

and we want to remap the dictionary removing all the negative elements in the array:

dict = dict.mapValues { v in v.filter { $0 > 0} }
print(dict) // ["k1":[1,2]]
mugx
  • 9,869
  • 3
  • 43
  • 55