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
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
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 Int
s.
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.