Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get parameter value of enum in IF condition? [duplicate]

How do write this

switch parameter {
case .CaseA(let valueA):
   print(valueA)
}

as an If condition statement? This doesn't work:

if parameter == .CaseA(let valueA) {
   print(valueA)
}
like image 220
Manuel Avatar asked Mar 27 '16 13:03

Manuel


1 Answers

You can use if case as follows

enum Foo {
    case A(Int)
    case B(String)
}

let parameter = Foo.A(42)

/* if case ... */
if case .A(let valueA) = parameter {
    print(valueA) // 42
}

The if case pattern matching is equivalent to a switch pattern matching with an empty (non-used) default case, e.g.

/* switch ... */
switch parameter {
case .A(let valueA):
    print(valueA) // 42
case _: ()
}

For details, see the Language Reference - Patterns.

like image 98
dfrib Avatar answered Oct 07 '22 01:10

dfrib