Search code examples
iosswiftif-statementswitch-statement

Switch statement for matching substrings of a String


Im trying to ask for some values from a variable. The variable is going to have the description of the weather and I want to ask for specific words in order to show different images (like sun, rain or so).
I have code like this:

if self.descriptionWeather.description.rangeOfString("clear") != nil {
    self.imageWeather.image = self.soleadoImage
}
if self.descriptionWeather.description.rangeOfString("rain") != nil {
    self.imageWeather.image = self.soleadoImage
}
if self.descriptionWeather.description.rangeOfString("broken clouds") != nil {
    self.imageWeather.image = self.nubladoImage
}

When I tried to add an "OR" condition, Xcode gives me some weird errors.

Is it possible to do a switch sentence with that? Or anyone knows how to do add an OR condition to the if clause?


Solution

  • Swift language has two kinds of OR operators - the bitwise ones | (single vertical line), and the logical ones || (double vertical line). In this situation you need a logical OR:

    if self.descriptionWeather.description.rangeOfString("Clear") != nil || self.descriptionWeather.description.rangeOfString("clear") != nil {
        self.imageWeather.image = self.soleadoImage
    }
    

    Unlike Objective-C where you could get away with a bitwise OR in exchange for getting a slightly different run-time semantic, Swift requires a logical OR in the expression above.