【问题标题】:Swift 2.2 - Using initialiser with variadic parameters of class typeSwift 2.2 - 使用带有类类型可变参数的初始化程序
【发布时间】:2017-01-07 21:52:19
【问题描述】:

在 Swift 2.2 中,我有以下类:

protocol Base {}

class FirstImpl: Base {}

class SecondImpl: Base {}

class Container {
    private var typeNames = Set<String>()

    init(_ types: Base.Type...) {
       for type in types {
           typeNames.insert(String(type))
       }
    }
}

如果我只向容器添加一个类类型,那么它编译得很好:

let c = Container(FirstImpl)

但是如果我开始添加更多的类类型,那么它将无法编译:

let c = Container(FirstImpl, SecondImpl)

构建错误是:

无法将类型“(FirstImpl,SecondImpl).Type”的值转换为预期的参数类型“Base.Type”

这是 Swift 编译器的限制还是我做错了什么?

【问题讨论】:

    标签: swift initialization variadic


    【解决方案1】:

    这是一个令人困惑的错误消息,但问题是您需要使用.self 才能在将类传递给函数时使用refer to the types。因此,您需要这样做:

    let c = Container(FirstImpl.self, SecondImpl.self)
    

    您的第一个不使用 .self 编译的示例实际上是 a bug(从 Swift 3 开始已解决) - 请参阅 this Q&A 了解更多信息。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-30
      • 2016-10-20
      • 2018-02-06
      相关资源
      最近更新 更多