Skip to content

Instantly share code, notes, and snippets.

@rkawajiri
Last active March 23, 2016 05:59
Show Gist options
  • Save rkawajiri/8ce67c1dd096353a2cb1 to your computer and use it in GitHub Desktop.
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
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