Last active
November 1, 2019 05:08
-
-
Save ijoshsmith/0c966b1752b9a5722e23 to your computer and use it in GitHub Desktop.
Create Swift Dictionary from Array
This file contains hidden or 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
/** | |
Creates a dictionary with an optional | |
entry for every element in an array. | |
*/ | |
func toDictionary<E, K, V>( | |
array: [E], | |
transformer: (element: E) -> (key: K, value: V)?) | |
-> Dictionary<K, V> | |
{ | |
return array.reduce([:]) { | |
(var dict, e) in | |
if let (key, value) = transformer(element: e) | |
{ | |
dict[key] = value | |
} | |
return dict | |
} | |
} | |
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 dictionary = toDictionary(people) { ($0.name, $0.age) } | |
println(dictionary) | |
// Prints: [Billy: 42, David: 24, Maria: 99] |
What about making this without that var
?
This is my suggestion of the extension using the reduce(into:) method of the swift standard library
extension Collection {
func dictionary<K:Hashable, V>(transform:(_ element: Iterator.Element) -> (key:K, value:V)) -> [K : V] {
return self.reduce(into: [K : V]()) { (accu, current) in
let kvp = transform(current)
accu[kvp.key] = kvp.value
}
}
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
In case people are looking for a Swift 3 version
And you'd use it something like this
Or, for those who might prefer an initialiser pattern:
Which rounds out to