2017-08-08 59 views
0

我試圖實現返回一般枚舉值,並確定它的參數之一的通用枚舉值。返回與特定相關的數據

像這樣的事情,因爲這個枚舉:

enum { 
state1(apple: Apple, color: Color) 
state2(pear: Pear, color: Color) 
... 
} 

我希望能夠返回的狀態,並確定它的價值觀之一。

... 
switch state { 
case .state1(_, _), .state2(_, _): 
return state(...blue color...) 
} 

那是可能的嗎?

謝謝!

回答

0

我想你會能夠獲得最接近的是有一個開關caseenum的每個case。然後使用模式匹配得到你想要保持和重建所需的值的值。

事情是這樣的:

enum Fruit { 
    case state1(apple: Int, color: String) 
    case state2(pear: Int, color: String) 
} 

var state = Fruit.state2(pear: 5, color: "green") 

var newState: Fruit 

switch state { 
    case .state1(let x, _): 
     newState = .state1(apple: x, color: "blue") 
    case .state2(let x, _): 
     newState = .state2(pear: x, color: "blue") 
} 

print(newState) 
state2(pear: 5, color: "blue") 
+0

權。試圖避免重複代碼..也許一些與模板可以幫助。 – gerbil

相關問題