Search code examples
swiftdeclarative

Is there a declarative way to transform Array to Dictionary?


I want to get from this array of strings

let entries = ["x=5", "y=7", "z=10"]

to this

let keyValuePairs = ["x" : "5", "y" : "7", "z" : "10"]

I tried to use map but the problem seems to be that a key - value pair in a dictionary is not a distinct type, it's just in my mind, but not in the Dictionary type so I couldn't really provide a transform function because there is nothing to transform to. Plus map return an array so it's a no go.

Any ideas?


Solution

  • Use Swift 4's new reduce(into: Result) method:

    let keyValuePairs = entries.reduce(into: [String:String]()) { (dict, entry) in
        let key = String(entry.first!)
        let value = String(entry.last!)
        dict[entry.first!] = entry.last!
    }
    

    Of course, the splitting of your String could be improved.