Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
extension Array {
func toDict<K,V>(map: (Element) -> (K, V)?) -> [K: V] {
var dict = [K: V]()
for element in self {
if let (key, value) = map(element) {
dict[key] = value
}
}
return dict
}
}
// to use
let t = [(name: "tom", age: 23),(name: "jim", age: 32),(name:"bill", age: 45)]
let g = t.toDict { ($0.name, $0.age) }
// ["tom": 23, "jim": 32, "bill": 45]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment