Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract value from enum using guard or if case in Swift

Tags:

swift

I have enum with cases:

case one(value: myClassOne)
case two(value: myClassTwo)

I want to check value of that enum. Now i ended with:

switch self.model! {
case .one:
    // Great, my case here
default:
    break
}

But i rather want to do something like:

if case self.model(let value) is myClassOne { // do smth } // Not compiling

Is there is easy way to simply extract enum value and check it for some condition or class equality?

like image 533
Evgeniy Kleban Avatar asked Dec 06 '17 13:12

Evgeniy Kleban


1 Answers

This is the correct syntax:

if case .one(value: let value) = self.model {
    // do something with `value`
}

guard case .one(value: let value) = self.model else {
    //handle case where self.model != .one
}
// do something with `value`
like image 168
Alexander Avatar answered Oct 31 '22 22:10

Alexander