简体   繁体   中英

Extract associated value of enum case into a tuple

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?

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

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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