Last active
April 9, 2017 18:51
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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