2016-08-05 49 views
2

我想弄清楚是否有可能通过枚举的类型传递相同的方式,你可以在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" 
     } 
    } 
} 

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

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的签名是什么?

回答

4

您可以为了做到这一点使用泛型,定义函数的参数是给定的TT.Type)元类型,如该TRawRepresentable,其RawValueInt。这将允许您传入FooBar的元类型。

func justAnExample<T : RawRepresentable>(_ whichEnum: 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 = whichEnum.init(rawValue: 0) else { return } 
    print("description: \(val)") 
} 

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

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

注意,之前斯威夫特3,你可以省略.self(它获取使用元)从参数,但是如果你这样做的雨燕3将生成一个警告。

+0

很好的链接到SO文档+1 –

-1

一种解决方案是为RawRepresentable,E.G.

extension RawRepresentable where RawValue == Int{ 

    static func testPrint() { 
     print(Self(rawValue: 0)) 
    } 
} 
enum Thing: Int { 
    case Test = 0 
} 
// prints "Optional(Thing.Test)" 
Thing.testPrint() 

那么你不必担心传递任何东西。当然,它不仅适用于枚举

+0

这没有帮助,因为我没有“事”。我试图通过'ThingA'或'ThingB'作为参数, – Kevin

+0

如果它是ThingA:Int和ThingB:Int应该没问题。您也可以为任何其他RawValue类型编写扩展 – PeejWeej

+0

但这并不能解决问题。我想调用'someOtherMethod(Thing)',而不是'Thing.testPrint()' – Kevin

相关问题