将枚举案例的关联值提取到元组中 [英] Extract associated value of enum case into a tuple
本文介绍了将枚举案例的关联值提取到元组中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我知道如何使用switch语句在枚举案例中提取关联值:
I know how to extract associated values in enum cases using switch statement:
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)")
}
但是我想知道是否存在一种使用元组提取关联值的方法。
But I was wondering if there is a way to extract associated value using tuples.
我尝试了
let (first, second, third, fourth) = productBarcode
<如预期的那样,它没有用。有没有办法将枚举案例的关联值转换为元组?还是不可能?
As expected, it did not work. Is there a way to turn associated value of enum cases into a tuple? or it is not possible?
推荐答案
如果情况允许,您可以将模式匹配与一起使用
提取一个特定枚举值的
关联值:
You can use pattern matching with if case let
to extract the
associated value of one specific enumeration value:
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)
}
这篇关于将枚举案例的关联值提取到元组中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文