根据我的理解,Swift的map
函数执行以下操作:
SequenceType
SequenceType
的“内容”,且元素数量不会发生变化例如:
我们有2个班级牛奶和奶酪。我们获得了 Cheese 的构造函数,如下所示:
init(withMilk milk: Milk) {
self.milk = milk
}
给定一系列 Milk 对象,我们将 Milk 对象数组转换为 Cheese 对象,如下所示:
let arrayOfCheese = arrayOfMilk.map { Cheese(withMilk: $0) }
这对我来说很好。但现在我想要比普通奶酪更多的东西。我需要来自各地的食材:
let arrayOfSuperCheese = arrayOfMilk.map {
let cheese = Cheese(usingMilk: $0)
let sulfur = Sulfur()
let minerals = Minerals()
let mixer = Mixer()
let superCheese = mixer.mixIn(sulphur: sulphur, minerals: minerals)
return superCheese
}
编译告诉我:
Cannot invoke 'map' with an argument list of type '(@noescape (Element) throws -> _)
上面的例子大致是我现在遇到的问题。如果这个例子有意义,请告诉我。
答案 0 :(得分:2)
这非常复杂,无法合理推断闭包签名。所以指定它:
let arrayOfSuperCheese = arrayOfMilk.map { (milk: Milk) -> Cheese in
let cheese = Cheese(usingMilk: milk)
let sulfur = Sulfur()
let minerals = Minerals()
let mixer = Mixer()
let superCheese = mixer.mixIn(sulfur: sulfur, minerals: minerals)
return superCheese
}