2

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?

halfer
  • 19,824
  • 17
  • 99
  • 186
Thor
  • 9,638
  • 15
  • 62
  • 137

2 Answers2

5

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)
}
Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382
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)

Ankit Thakur
  • 4,739
  • 1
  • 19
  • 35