我知道如何使用 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)")
}
但我想知道是否有一种方法可以使用元组提取关联值。
I tried
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)
}
or
if case let Barcode.upc(tuple) = productBarcode {
print(tuple) // (8, 10, 15, 2)
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)