在嵌套类中名为“Type”的枚举失败 [英] Enum named `Type` in nested class fails
问题描述
由于某种原因,使用嵌套枚举名为 Type
的嵌套类不能与swift编译器一起使用。
class A {
class B {
枚举类型{
case One
case两个
}
让myC:键入
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
上述代码产生两个错误: code>'ABType'不能转换为'ABType'和'ABType.Type'没有名为Two的成员
。
以下情况可以正常工作:
-
class B
class A
-
let b = AB (myC:.Two)
-
枚举C
而不是枚举类型
这是Swift中的一个错误还是是否是这种行为? code>键入我们不应该使用的保留名称。
类型是指B类的元类型,这就是为什么编译器不喜欢你定义一个名为'Type'的内部枚举。
你可以使用在变量中键入
/常量声明做类反射:
class A {
required init(){}
}
class B {
var a:A.Type
var aInstance:A
init(){
a = A.自己
aInstance = a()
}
}
For some reason, having a nested class with an nested enum named Type
dosen't play well with the swift compiler.
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
The above code produces two errors: 'A.B.Type' is not convertible to 'A.B.Type'
and 'A.B.Type.Type' does not have a member named 'Two'
.
The following cases does work:
class B
outside ofclass A
let b = A.B(myC: .Two)
enum C
instead ofenum Type
It this a bug in Swift or is this intended behaviour? Is Type
a reserved name which we shouldn't use?
B.Type refers to class B's metatype, which is why the compiler doesn't like you defining an inner-enum with the name 'Type'.
You can use Type
in variable/constant declaration to do class reflection:
class A {
required init() {}
}
class B {
var a: A.Type
var aInstance: A
init() {
a = A.self
aInstance = a()
}
}
这篇关于在嵌套类中名为“Type”的枚举失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!