Enum named `Type` in nested class fails

匿名 (未验证) 提交于 2019-12-03 00:52:01

问题:

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



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!