我知道如何使用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
正如所料,它没有用。有没有办法将枚举案例的相关值转换为元组?还是不可能?
答案 0 :(得分:4)
您可以使用与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)
}
答案 1 :(得分:1)
您可以在此方案中使用元组
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)