将枚举大小写的关联值提取到一个元组中

我知道如何使用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) } 

在这种情况下你可以使用元组

 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)") } typealias tupleBarcode = (one:Int, two:Int,three: Int, three:Int) switch productBarcode { case let .upc(tupleBarcode): print("upc: \(tupleBarcode)") case .quCode(let productCode): print("quCode \(productCode)") } 

upc:(8,10,15,2)

upc:(8,10,15,2)