Skip to content

Instantly share code, notes, and snippets.

@tbartelmess
Last active April 9, 2017 18:51
Show Gist options
  • Save tbartelmess/7b2c4bb54f2f27b7b517d7c79a77a0ea to your computer and use it in GitHub Desktop.
Save tbartelmess/7b2c4bb54f2f27b7b517d7c79a77a0ea to your computer and use it in GitHub Desktop.
An extension to the Collection Type to create a dictionary using a transform closure.
extension Collection {
// Create a Dictionary from a collection using a transformer.
// The transformer function takes an element from the collection and returns a tuple
// with the key/value pair.
func dictionary<K, V>(transform:(_ element: Iterator.Element) -> (K, V)) -> [K : V] {
var dictionary = [K : V]()
self.forEach { element in
let (key, value) = transform(element)
dictionary[key] = value
}
return dictionary
}
}
let col = [1,2,3,4]
let powers = col.dictionary { (x) -> (Int, Int) in
(x, x*x)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment