出于某种原因,具有名为 Type
的嵌套枚举的嵌套类不能很好地与 swift 编译器配合使用。
class A {
class B {
enum Type {
case One
case Two
}
let myC: Type
init(myC: Type) {
self.myC = myC
}
}
func getB(myC: B.Type) -> B {
return B(myC: myC) // ERROR 1
}
}
let a = A()
let b = a.getB(.Two) // ERROR 2
上面的代码产生了两个错误:'A.B.Type' is not convertible to 'A.B.Type'
和 'A.B.Type.Type' does not have a member named 'Two'
.
以下情况确实有效:
class B
在class A
之外
让 b = A.B(myC: .Two)
enum C
而不是enum Type
这是 Swift 中的错误还是这是预期的行为? Type
是我们不应该使用的保留名称吗?
最佳答案
B.Type 指的是类 B 的元类型,这就是为什么编译器不喜欢您定义名称为“Type”的内部枚举的原因。
您可以在变量/常量声明中使用Type
来进行类反射:
class A {
required init() {}
}
class B {
var a: A.Type
var aInstance: A
init() {
a = A.self
aInstance = a()
}
}
关于swift - 嵌套类中名为 `Type` 的枚举失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28608936/