swift - 嵌套类中名为 `Type` 的枚举失败

标签 swift enums

出于某种原因,具有名为 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 Bclass A
  • 之外
  • 让 b = A.B(myC: .Two)
  • enum C 而不是 enum Type

这是 Swift 中的错误还是这是预期的行为? 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()
    }
}

关于swift - 嵌套类中名为 `Type` 的枚举失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28608936/

相关文章:

c# - 从库类公开枚举

c++ - 如何将 strcat 与 ENUM 一起使用?

Json 模式检查所有项目枚举是否存在于对象数组中

swift - 无法识别的选择器发送到实例(swift)

swift - 如何在静态 UITableviewCell 中使用 setTitleForState 更改 UIButton 标题

ios - 如何使用用户默认值保存和获取按钮启用和禁用值

c# - 有没有办法使 ToEnum 通用

swift - Rx swift : Observe viewDidLoad from view model without Subjects

ios - 尝试在启动应用程序时使用 Swift 在 Xcode 中查找用户位置但出现可选错误?

c++ - C++ 类中嵌套类型的快捷方式