swift - 可以在 Swift 中将枚举类型名称作为参数传递吗?

标签 swift types enums

我想弄清楚是否可以像在 Swift 中传递 Class 对象一样传递枚举的类型。

我的实际用例比这复杂一点,但为了便于讨论,假设我有两个 Int 枚举:

enum Foo: Int, CustomStringConvertible {
    case firstFoo = 0
    case anotherFoo = 1
    var description: String {
        switch self {
        case .firstFoo:
            return "Hello Foo"
        case .anotherFoo:
            return "Goodbye Foo"
        }
    }
}

enum Bar: Int, CustomStringConvertible {
    case firstBar = 0
    case anotherBar = 1
    var description: String {
        switch self {
        case . firstBar:
            return "Hello Bar"
        case . anotherBar:
            return "Goodbye Bar"
        }
    }
}

我希望能够编写这样的函数:

func justAnExample(whichEnum: enum) {
    let val = whichEnum(rawValue: 0)
    print("description: \(String(val))")
}

然后像这样使用它:

justAnExample(Foo)
// prints: "description: Hello Foo"
justAnExample(Bar)
// prints: "description: Hello Bar"

这可能吗?如果是这样,函数声明中whichEnum 的签名是什么?

最佳答案

您可以利用具有原始值的枚举自动符合 RawRepresentable 协议(protocol)这一事实。您可以定义一个通用函数,该函数采用给定类型 T(拼写为 T.Type)的元类型参数,其中 TRawRepresentable而且,在你的情况下,它的 RawValueInt

这将允许您传入 FooBar 的元类型,拼写为 Foo.selfBar.self 分别为:

func justAnExample<T : RawRepresentable>(_ enumType: T.Type) where T.RawValue == Int {

  // Note that an explicit use of init is required when creating an instance from a
  // metatype. We're also using a guard, as `init?(rawValue:)` is failable.
  guard let val = enumType.init(rawValue: 0) else { return }
  print("description: \(val)")
}

justAnExample(Foo.self) // prints: "description: Hello Foo"
justAnExample(Bar.self) // prints: "description: Hello Bar"

关于swift - 可以在 Swift 中将枚举类型名称作为参数传递吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38793536/

相关文章:

types - 如何在 Kotlin 中正确处理大于 127 的字节值?

swift - 如何在方法中使用其他类的枚举?

ios - 当 JSON 输入表示 Codable 类型的多个子类时使用 Codable

ios - 在 SceneDelegate 中分配的 Observable 属性变为 nil

swift - URL 方案不适用于 macOS

scala - 为伴随对象中的方法指定类型差异的正确方法是什么

c - 取消引用指向不完整类型的指针 [处理结构]

swift - 我如何在 Swift 中初始化这种包含属性但没有构造函数的枚举?

python - 'type' 对象在使用 django_enums 时不可迭代

ios - 多点连接 手动连接/管理对等点