0

I' have dictionary

var dict: [String: [String]] = ["key1": ["1", "111"], "key2": ["22", "222"]]

How i can convert it to [String: [Int]] using map function

["key1": [1, 111], "key2": [22, 222]]

NOT by using for OR forEach loop

Abhishek Thapliyal
  • 3,497
  • 6
  • 30
  • 69

1 Answers1

5

Swift 4

You can use mapValues (introduced in Swift 4) with an array map as follows

let newDict = dict.mapValues { value in 
    value.map { Int($0)!}
}

Note that your program will crash if the values inside your array can not be converted to Ints.

Swift 3

In Swift 3, however, there is no mapValues. Fortunately, with this extension (source: https://stackoverflow.com/a/24219069):

extension Dictionary {
    init(_ pairs: [Element]) {
        self.init()
        for (k, v) in pairs {
            self[k] = v
        }
    }
}

you can write

let newDict = Dictionary(dict.map { (key, value) in 
    (key, value.map{Int($0)!}) 
})

which will also achieve the desired result.

Papershine
  • 4,995
  • 2
  • 24
  • 48