2016-02-04 33 views
2

我有超過斯威夫特與關聯值的枚舉類型的開關case語句:我可以在案例模式中使用劇組嗎?

enum Foo { 
    case Something(let s: Any) 
    // … 
} 

我想使用模式匹配演員陣容,有點像這樣:

let foo: Foo = // … 
switch foo { 
    case .Something(let a as? SpecificType): 
     // … 
} 

在換句話說,我希望案例模式只有在演員成功後才能成功。那可能嗎?

回答

2

你的榜樣基本工作原理是:

enum Foo { 
    case Something(s: Any) 
} 

let foo = Foo.Something(s: "Success") 
switch foo { 
case .Something(let a as String): 
    print(a) 
default: 
    print("Fail") 
} 

如果更換 「成功」 與如數字1它會打印「失敗」,而不是。那是你要的嗎?

+1

這比我的'where'子句更好,因爲我得到的值已經轉換爲正確的類型。謝謝! (我很接近,但我使用'as?'而不是'as',這是行不通的。) – zoul

4

您可以使用where子句:

enum Foo { 
    case Something(s: Any) 
} 

let foo: Foo = Foo.Something(s: "test") 
switch foo { 
case .Something(let a) where a is String: 
    print("Success") 
default: 
    print("Failed") 
} 
+0

幫助你打敗了我,但是是的 –

+0

非常感謝! – zoul

相關問題