使用Swift的地图时,你能传递初始化器而不是函数/闭包吗?

时间:2015-05-11 09:00:00

标签: swift

考虑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 感觉它与(String, String) -> Motorcycle初始化程序具有相同的类型(Motorcycle),我想知道是否有某种方法可以引用到Motorcycle初始值设定项,而不是genMotorcycle

换句话说,有没有办法有效地表达以下内容?

let motorcycles = map(data, Motorcycle)
// or
let motorcycles = map(data, Motorcycle.init)

1 个答案:

答案 0 :(得分:2)

“敲门声。” “谁在那?” “输入验证器。” “输入验证器是谁?” true

更新:从Swift 2.0开始,你确实可以传递init,例如。 String.initMotorcycle.init