Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift 2 if case syntax with enum having associated values

I'm stuck with some really simple syntax I guess, but I can't find how to solve it.

  • First of all here's the setup, let me introduce a nice enum with multiple associated values

    enum Entity {
        case City(data: CityData, position: NSRange)
        case Date(date: NSDate)
        case Service
    }
    
  • Then I would like to check if a field of some dictionary is a city and if it is, deal with its data and position... The only way I could manage is via a switch!!!

    if let city = result["ABC"] {
        switch city {
        case .City(data:let data, position:let position): // Do something with data and position
        default: // Do nothing
        }
    }
    

And I was wondering if the if casesyntax could be of any help...

But I could not find it (may be the tiredness, I hope...)

I'm looking for something like that:

if case result["ABC"] == .City(data:let data, position:let position) { 
    // Do something with data and position
}

So I'm sure it's obvious, but I've missed it... So if you can help, that would be great.

Thanks in advance.

like image 465
Zaphod Avatar asked Oct 15 '25 11:10

Zaphod


1 Answers

Swift dictionaries return optional values. So, using switch, you should do:

switch result["ABC"] {
case let .City(data, position)?:
   // Do something with data and position
default:
  break
}

Using if pattern matching:

if case let .City(data, position)? = results["ABC"] {
  // Do something with data and position
}
like image 90
Wallace Campos Avatar answered Oct 18 '25 04:10

Wallace Campos



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!