Skip to content

Instantly share code, notes, and snippets.

@TheNamesJamesW
Created November 12, 2016 18:26
Show Gist options
  • Save TheNamesJamesW/3b4dcc2332964c279058e42986d8c220 to your computer and use it in GitHub Desktop.
Save TheNamesJamesW/3b4dcc2332964c279058e42986d8c220 to your computer and use it in GitHub Desktop.
Create a Dictionary from any collection (updated from https://gist.github.com/ijoshsmith/0c966b1752b9a5722e23)
extension Collection {
func dictionary<K, V>(transform:(_ element: Iterator.Element) -> [K : V]) -> [K : V] {
var dictionary = [K : V]()
self.forEach { element in
for (key, value) in transform(element) {
dictionary[key] = value
}
}
return dictionary
}
}
struct Person {
let name: String
let age: Int
}
let people = [
Person(name: "Billy", age: 42),
Person(name: "David", age: 24),
Person(name: "Maria", age: 99)]
let dictionary1 = people.dictionary { [$0.name : $0.age] }
//["Billy": 42, "Maria": 99, "David": 24]
// Or, for those who might prefer an initialiser pattern:
extension Dictionary {
init<C: Collection>(_ collection: C, transform:(_ element: C.Iterator.Element) -> [Key : Value]) {
self.init()
collection.forEach { (element) in
for (k, v) in transform(element) {
self[k] = v
}
}
}
}
let dictionary2 = Dictionary(people) { [$0.name : $0.age] }
//["Billy": 42, "Maria": 99, "David": 24]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment