ios - 将枚举案例的关联值提取到元组中

标签 ios swift enums tuples

我知道如何使用 switch 语句提取枚举案例中的关联值:

enum Barcode {
    case upc(Int, Int, Int, Int)
    case quCode(String)
}
var productBarcode = Barcode.upc(8, 10, 15, 2)

switch productBarcode {
case  let .upc(one, two, three, four):
    print("upc: \(one, two, three, four)")
case .quCode(let productCode):
    print("quCode \(productCode)")
}

但我想知道是否有一种方法可以使用元组提取关联值。

我试过了

let (first, second, third, fourth) = productBarcode

正如预期的那样,它没有起作用。有没有办法将枚举案例的关联值转换为元组?还是不可能?

最佳答案

您可以使用 if case let 的模式匹配来提取 一个特定枚举值的关联值:

if case let Barcode.upc(first, second, third, fourth) = productBarcode {
    print((first, second, third, fourth)) // (8, 10, 15, 2)
}

if case let Barcode.upc(tuple) = productBarcode {
    print(tuple) // (8, 10, 15, 2)
}

关于ios - 将枚举案例的关联值提取到元组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40416274/

相关文章:

ios - 二进制数据允许外部存储 - 错误 : Compilation failed for data model at path

ios - ARKit中动画播放时如何获取3D对象的当前位置?

swift - 如何在 RxSwift 中顺序循环一个可观察对象?

ios - 我应该如何快速上传带有图像的文本

c# - 创建将 T 约束为枚举的通用方法

ios - 在 UITableViewController 模板中缺少 TableViewCell 分配

ios - Xcode 停止随机识别类类型

ios - 带有离线 URL 的 NSURLSession

c - 枚举值解析

像 Swift 一样使用 Enum 进行 Objective-C 错误处理