考虑摩托车名和描述的Dictionary
:
let data = ["Betty" : "Very fast", "Mike" : "Easy going"]
和一个具有两个属性的简单Motorcycle
类。
class Motorcycle {
let name: String
let description: String
init(name: String, description: String) {
self.name = name
self.description = description
}
}
aaand一个人为的函数,接受两个 String
值并返回 Motorcycle
。
func genMotorcycle(name: String, desc: String) -> Motorcycle {
return Motorcycle(name: name, description: desc)
}
现在,假设您想将Dictionary
转换为[Motorcycle]
,则可以:
let motorcycles = map(data) { Motorcycle(name: $0, description: $1) }
或使用人为的genMotorcycle
函数:
let motorcycles = map(data, genMotorcycle)
由于 genMotorcycle
感觉喜欢它具有与Motorcycle
初始化器相同的类型((String, String) -> Motorcycle
),因此我想知道是否有某种方法可以参考Motorcycle
初始化器而不是genMotorcycle
。/p>
换句话说,有没有办法有效地表达以下方式?
let motorcycles = map(data, Motorcycle)
// or
let motorcycles = map(data, Motorcycle.init)
no。
"敲门。"谁在那儿?"输入验证器。"输入验证者谁?" true
更新:从Swift 2.0开始,您确实可以通过INIT,例如。String.init
或Motorcycle.init
。