Extract associated value of enum case into a tuple

99封情书 提交于 2019-12-11 05:05:07

问题


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.

I tried

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?


回答1:


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)
}

or

if case let Barcode.upc(tuple) = productBarcode {
    print(tuple) // (8, 10, 15, 2)
}



回答2:


You can use tuples in this scenario

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)



来源:https://stackoverflow.com/questions/40416274/extract-associated-value-of-enum-case-into-a-tuple

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!