在使用 Swift 的映射时,你能传递一个初始值设定项而不是一个函数/闭包吗?

  • 本文关键字:一个 闭包 函数 Swift 映射 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 感觉喜欢它具有与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.initMotorcycle.init

相关内容

最新更新