Xcode7.3にしたら、closureとかの引数をvarにすると警告が出るようになっちゃいましたね。Swift3からは正式に出来なくなるようです。
今までは、arrayからdictionaryを作るときはreduce使ってたんですが、varじゃないと書きにくいですね。それならいっその事、extensionでやってみました。
SequenceType+toDictionary.swift
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
}
}