2017-08-08 58 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

相关问题