Reputation: 7270
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 case
syntax 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.
Upvotes: 4
Views: 1198
Reputation: 1301
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
}
Upvotes: 13