gpt4 book ai didi

swift - 返回具有特定关联数据的通用枚举值

转载 作者:行者123 更新时间:2023-11-30 12:14:47 25 4
gpt4 key购买 nike

我正在尝试返回一个通用枚举值并确定它的参数之一。

给定这个枚举,类似这样的事情:

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com