在 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 编译器的限制还是我做错了什么?
最佳答案
这是一条令人困惑的错误消息,但问题是您需要使用 .self
才能 refer to the types将类传递给函数时的类。因此你需要这样做:
let c = Container(FirstImpl.self, SecondImpl.self)
您的第一个不使用 .self
进行编译的示例实际上是 a bug (从 Swift 3 开始已解决) – 请参阅 this Q&A了解更多信息。
关于Swift 2.2 - 将初始化程序与类类型的可变参数一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39247359/