Cases with Parameters
We can add parameters to each case of an enum
. Imagine we have an enum
of type Color
with two options, rgb
and hex
. We can include parameters for each option by defining the name and type of each.
enum Color {
case rgb(r: Int, g: Int, b: Int)
case hex(code: String)
}
This way, when we create an enum of type Color
, we can assign the values that define the color.
let colorOne = Color.rgb(r: 24, g: 123, b: 250)
let colorTwo = Color.hex(code: "#EA4F12")
When using our enum
in a switch
, we will have access to these parameters.
switch colorOne {
case .rgb(let r, let g, let b):
print("RGB Color: \(r), \(g), \(b)")
case .hex(let code):
print("HEX Color: \(code)")
}
// Console output: RGB Color: 24, 123, 250
if case
If we want to check the value of a specific case without using a full switch
statement, we can use an if
statement like this:
if case .rgb(let r, let g, let b) = colorOne {
print("RGB Color: \(r), \(g), \(b)")
}
Be the first to comment