当我已经知道枚举 case 语句并想要获取其关联值时,是否有比使用 switch 语句提取关联值更干净的方法?
必须提出 switch 语句、提供多种情况或默认情况只是为了提取关联值,这太花哨了。
enum CircularReasoning {
case justPi(pi: Double)
case pizzaPie(howMany: Int)
}
var piInTheSky : Double
let whatLogic = CircularReasoning(pi: 3.1415926)
⬇️ 𝘸𝘢𝘯𝘵 𝘵𝘰 𝘢𝘷𝘰𝘪𝘥 ⬇️
switch whatLogic {
case .justPi(let pi):
piInTheSky = pi!
default:
break
}
最佳答案
您可以使用if case .<enum_case>(let value)
就像 TylerP 的例子一样,
或if case let .<enum_case>(value)
:
enum Foo {
case anInt(Int)
case aFloat(Float)
}
let aFoo: Foo = .anInt(9)
// Example of `if case .<enum_case)(let value)` syntax:
if case .anInt(let aValue) = aFoo {
print("aFoo = anInt(\(aValue))")
// Example of `if case let .enum_case(value)` syntax:
} else if case let .aFloat(aValue) = aFoo {
print("aFoo = aFloat(\(aValue))")
}
两者都有效。我不确定为什么该语言包含这两种变体。
如果您只关心一种枚举类型,那么 if
语法对我来说很有意义。如果您正在处理多个可能的枚举值,那么 switch 版本似乎更干净。
关于swift - Swift 有没有办法在不使用 switch 语句的情况下获取关联值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73271619/