This question already has answers here:
Can you use map to create instances without a wrapper?

(3 个回答)


6年前关闭。




考虑摩托车名称和描述的 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
    }

}

Aa 和一个人为的函数,它接受两个 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)

最佳答案

编号

“敲敲。”
“谁在那儿?”
“一个输入验证器。”
“输入验证器谁?”true
更新:从 Swift 2.0 开始,您确实可以传递 init,例如。 String.initMotorcycle.init

10-06 14:05