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/

相关文章:

ios - 通用类型编译器错误的 Swift 扩展

ios - 当外设需要特殊 ACK 时,CoreBluetooth 和状态保存和恢复

java - play framework - 在路由中绑定(bind)枚举

objective-c - Objective-C 中的 typedef 枚举是什么?

ios - UIImagePickerController - 默认情况下如何访问前置摄像头?

ios - 如何让我的 UISwipeGestureRecognizer 工作?

typescript - 如何根据函数数组参数推断函数返回类型?

c# 转换为从类型名获取的类型作为字符串

c++ - 在 C++ 中获取类名有哪些好的技巧?

c - 您是否需要在 C 枚举的最后一个成员之后添加一个额外的 ","?