繁体   English   中英

将枚举案例的关联值提取到元组中

[英]Extract associated value of enum case into a tuple

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM