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