首页 > 解决方案 > 是否可以让枚举类型将它们存储在 Swift 4 的集合中?

问题描述

我有多个符合特定协议的 Enum 类型,我想将它们的类型存储在一个数组中。但我似乎找不到办法做到这一点。

这是简化的代码。

protocol TestEnumProtocol {
    static var name: String { get }
    static var count: Int { get }
}

enum Test1 : TestEnumProtocol {
    static var name: String { return "Test1" }
    static var count: Int { return 2 }

    case A
    case B
}

enum Test2 : TestEnumProtocol {
    static var name: String { return "Test2" }
    static var count: Int { return 3 }

    case AA
    case BB
    case CC
}

var enums: [TestEnumProtocol.self] = [Test1.self, Test2.self] // Compile Error

基本上,我需要处理多个多变量测试,并且我想让我的逻辑通用。

我知道我可以通过使用类来实现这一点,但我想知道是否有使用枚举的方法,因为 Enum 在这种情况下似乎更直观。(至少对我来说)

标签: swiftenumsswift4

解决方案


推荐阅读