Skip to content

Instantly share code, notes, and snippets.

@apocolipse
Created November 15, 2015 19:53
Show Gist options
  • Save apocolipse/bd59898bdd020494fdd7 to your computer and use it in GitHub Desktop.
Save apocolipse/bd59898bdd020494fdd7 to your computer and use it in GitHub Desktop.
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