2016-08-05 50 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

相關問題