swift - Swift 有没有办法在不使用 switch 语句的情况下获取关联值?

标签 swift enums switch-statement let associated-value

当我已经知道枚举 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/

相关文章:

ios - 对于键 setDefaultLabelText,此类不符合键值编码。

java - 如何从 Java 中的 Enum 值返回具有所有属性的 Enum 对象

c++ - 如何忽略定义(VS2008)

java - JOptionPane switch 语句循环

c# - ReSharper 提示它生成的 switch 语句—— "Cannot resolve symbol ..."

ios - swift - 如何从服务器获取 JSON 响应

ios - 如何快速将耳机的声音从左移到右?

c# - 如何将枚举作为参数传递?

Java 将 switch 语句转换为另一种类型

ios - View Controller 到达前端时必须刷新自身