我正在尝试返回一个通用枚举值并确定它的参数之一。
给定这个枚举,类似这样的事情:
enum {
state1(apple: Apple, color: Color)
state2(pear: Pear, color: Color)
...
}
我希望能够返回一个状态,并确定其值之一。
...
switch state {
case .state1(_, _), .state2(_, _):
return state(...blue color...)
}
可以这样做吗?
谢谢!
最佳答案
我认为您能够获得的最接近的结果是为 enum
的每个 case
提供一个 switch 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")
关于swift - 返回具有特定关联数据的通用枚举值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45566321/