Last active
March 23, 2016 05:59
-
-
Save rkawajiri/8ce67c1dd096353a2cb1 to your computer and use it in GitHub Desktop.
`toDictionary` by Extension of SequenceType ref: http://qiita.com/ryoma_kawajiri/items/83f13cc45396e221e24e
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
extension SequenceType { | |
func toDictionary<K, V>() -> [K: V] { | |
var dictionary: [K: V] = [:] | |
self.forEach { e in | |
if let kv = e as? (K, V) { | |
dictionary[kv.0] = kv.1 | |
} | |
} | |
return dictionary | |
} | |
func toDictionary<K, V>(transform: (element: Self.Generator.Element) -> (key: K, value: V)?) -> [K: V] { | |
var dictionary: [K: V] = [:] | |
self.forEach { e in | |
guard let (key, value) = transform(element: e) else { | |
return | |
} | |
dictionary[key] = value | |
} | |
return dictionary | |
} | |
func toDictionary<K, V>(combine: (value1: V, value2: V) -> V?) -> [K: V] { | |
var dictionary: [K: V] = [:] | |
self.forEach { e in | |
guard let kv = e as? (K, V) else { | |
return | |
} | |
let (key, value2) = kv | |
if let value1 = dictionary[key] { | |
dictionary[key] = combine(value1: value1, value2: value2) | |
} else { | |
dictionary[key] = value2 | |
} | |
} | |
return dictionary | |
} | |
func toDictionary<K, V>(transform transform: (element: Self.Generator.Element) -> (key: K, value: V)?, combine: (value1: V, value2: V) -> V?) -> [K: V] { | |
var dictionary: [K: V] = [:] | |
self.forEach { e in | |
guard let (key, value2) = transform(element: e) else { | |
return | |
} | |
if let value1 = dictionary[key] { | |
dictionary[key] = combine(value1: value1, value2: value2) | |
} else { | |
dictionary[key] = value2 | |
} | |
} | |
return dictionary | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment