将 enum case 的关联值提取到一个元组中

Tho*_*hor 2 enums tuples ios swift

我知道如何使用 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)")
}
Run Code Online (Sandbox Code Playgroud)

但我想知道是否有办法使用元组提取关联值。

我试过

let (first, second, third, fourth) = productBarcode
Run Code Online (Sandbox Code Playgroud)

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

Mar*_*n R 5

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

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

或者

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