可以将枚举类型名称作为参数传递给Swift吗?

Kev*_*vin 9 enums types swift

我试图弄清楚是否可以以与Class在Swift中传递对象相同的方式传递枚举类型.

我的实际用例比这更复杂,但是为了讨论,我想说我有两个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"
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

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

func justAnExample(whichEnum: enum) {
    let val = whichEnum(rawValue: 0)
    print("description: \(String(val))")
}
Run Code Online (Sandbox Code Playgroud)

然后像这样使用它:

justAnExample(Foo)
// prints: "description: Hello Foo"
justAnExample(Bar)
// prints: "description: Hello Bar"
Run Code Online (Sandbox Code Playgroud)

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

Ham*_*ish 11

您可以利用具有原始值的枚举自动符合RawRepresentable协议的事实.您可以定义一个通用的函数,它接受一个给定类型的元类型的参数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"
Run Code Online (Sandbox Code Playgroud)