Reputation: 10038
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?
Upvotes: 2
Views: 1813
Reputation: 4749
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)
Upvotes: 2
Reputation: 539705
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)
}
Upvotes: 5