gpt4 book ai didi

ios - swift enum 在单个 switch-case 中获取具有相同参数的多个 case 的关联值

转载 作者:可可西里 更新时间:2023-10-31 23:56:40 26 4
gpt4 key购买 nike

这是一个带有关联值的常见枚举。

enum MultiplierType {
case width(Double)
case height(Double)
case xxxxx1(Double)
case xxxxx2(Double)
case xxxxx3(Double)

var value: Double {
switch self {
// Normal way.
case let .width(value):
return value
case let .height(value):
return value
case let .xxxxx1(value):
return value
...
}
}
}

我的问题是如何做到这一点?

var value: Double {
switch self {
// How to get the value in one case?
case let .width(value), .height(value), .xxx:
return value
}
}

或者

var value: Double {
switch self {
// How to get the value in one case?
case let .width, .height, .xxx (value):
return value
}
}

获取关联值最优雅的方法是什么?

最佳答案

您可以将多个枚举值放在同一行 case 中,但是您必须将 let 移到 () 中:

var value: Double {
switch self {
case .width(let value), .height(let value), .xxxxx1(let value):
return value
}
}

您可能希望将每个 enum 值放在单独的一行中:

var value: Double {
switch self {
case .width(let value),
.height(let value),
.xxxxx1(let value):
return value
}
}

不幸的是,这与使用具有关联值的 enum 一样优雅。如果不显式列出 enum,就无法获取关联值。

您只能在同一行中组合具有相同类型关联值的值,并且所有值都必须绑定(bind)到相同的变量名。这样,在随后的代码中,您就知道 value 已绑定(bind),并且无论哪个 enum 模式匹配,它的类型都是什么。

关于ios - swift enum 在单个 switch-case 中获取具有相同参数的多个 case 的关联值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52030390/

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