可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
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 of class A let b = A.B(myC: .Two) enum C instead of enum Type
It this a bug in Swift or is this intended behaviour? Is Type a reserved name which we shouldn't use?
回答1:
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() } }
回答2:
Yes, it's a reserved word. But you can go right ahead and use a reserved word as long as you mark it in backticks. This works fine:
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) } }
回答3:
Not allowed yet to comment on matt's answer, so I have to post as an answer
As of Swift 4.1 (and maybe 4.0), you now get a compiler error when you try to use the Type reserved word for a Type name (tested for nested enum like in the question):
Type member must not be named 'Type' since it would conflict with the 'foo.Type' expression