How to write this
switch parameter {
case .CaseA(let valueA):
print(valueA)
}
As an If condition statement? This does not work:
if parameter == .CaseA(let valueA) {
print(valueA)
}
enum Foo {
case A(Int)
case B(String)
}
let parameter = Foo.A(42)
/* if case ... */
if case .A(let valueA) = parameter {
print(valueA) // 42
}
if case pattern matching is equivalent For switch patterns that match the empty (unused) default case, for example,
/* switch ... */
switch parameter {
case .A(let valueA):
print(valueA) // 42
case _: ()
)
For more information, please refer to the Language Reference – Patterns .
See the answer in English> Get associated value from enumeration without switch/case 2
How to write this
switch parameter {
case .CaseA(let valueA):
print(valueA)
}
As an If condition statement? This does not work:
if parameter == .CaseA(let valueA) {
print(valueA)
}
If the situation is as follows, you can use
enum Foo {
case A(Int)
case B(String)
}
let parameter = Foo.A(42)
/* if case ... */
if case .A(let valueA) = parameter {
print(valueA) // 42
}
If case pattern matching is equivalent to a switch that matches the empty (unused) default case Mode, for example,
/* switch ... */
switch parameter {
case .A(let valueA):
print (valueA) // 42
case _: ()
)
For more information, please refer to the Language Reference – Patterns.