由于某些原因,使用名为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 A
之外的class B
let b = A.B(myC: .Two)
enum C
而不是enum Type
这是Swift中的一个bug还是中的一种行为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()
}
}
是的,这是一个保留字。但你可以直接使用一个保留字,只要你在后面打上记号。这很好:
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)
}
}