extension SequenceType {
func toDict<K : Hashable, V>
(@noescape convert: Generator.Element -> (K, V)) -> [K:V] {
var result: [K:V] = [:]
for x in self {
let (key, val) = convert(x)
result[key] = val
}
return result
}
}
dictionary.toDict { (n, l) in (n, newLogger(l.0, withLevel: level(l.1))) }
或者
extension Dictionary {
public init<
S : SequenceType where
S.Generator.Element == (Key, Value)
>(_ seq: S) {
self.init()
for (k, v) in seq { self[k] = v }
}
}
extension SequenceType {
func toDict<K : Hashable, V>
(@noescape convert: Generator.Element -> (K, V)) -> [K:V] {
return Dictionary(lazy(self).map(convert))
}
}
dictionary.toDict { (n, l) in (n, newLogger(l.0, withLevel: level(l.1))) }
或者
extension Dictionary {
func map<K : Hashable, V>(@noescape transform: (Key, Value) -> (K, V)) -> [K:V] {
var result: [K:V] = [:]
for x in self {
let (key, val) = transform(x)
result[key] = val
}
return result
}
}
dictionary
.map { (n, l) in (n, newLogger(l.0, withLevel: level(l.1))) }
Dictionary
吗?我讨厌依赖副作用来实现我的目标的想法...!(我甚至会选择返回一个数组,然后将其转换为字典...) - Zaphodvar
和let
、struct
和classes
,并且基本框架需要副作用,原本是用C和Objective-C编写的。因此,如果您想继续在Swift和iOS上进行编程,恐怕您必须熟悉非函数式编程技术。 - Renzo