嵌套 class 中名为“Type”的枚举失败
Enum named `Type` in nested class fails
出于某种原因,嵌套 class 和名为 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
之外
let b = A.B(myC: .Two)
enum C
而不是 enum Type
这是 Swift 中的错误还是 这是预期的行为? Type
是我们不应该使用的保留名称吗?
B.Type 指的是 class B 的元类型,这就是编译器不喜欢你定义名称为 'Type'.
的内部枚举的原因
您可以在 variable/constant 声明中使用 Type
来进行 class 反射:
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)
}
}
出于某种原因,嵌套 class 和名为 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
之外
let b = A.B(myC: .Two)
enum C
而不是enum Type
这是 Swift 中的错误还是 这是预期的行为? Type
是我们不应该使用的保留名称吗?
B.Type 指的是 class B 的元类型,这就是编译器不喜欢你定义名称为 'Type'.
的内部枚举的原因您可以在 variable/constant 声明中使用 Type
来进行 class 反射:
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)
}
}