Swift switch statement for matching substrings of a String Swift switch statement for matching substrings of a String ios ios

Swift switch statement for matching substrings of a String


I had a similar problem today and realized this question hasn't been updated since Swift 1! Here's how I solved it in Swift 4:

switch self.descriptionWeather.description {case let str where str.contains("Clear"):    print("clear")case let str where str.contains("rain"):    print("rain")case let str where str.contains("broken clouds"):    print("broken clouds")default:    break}


You can do this with a switch statement using value binding and a where clause. But convert the string to lowercase first!

var desc = "Going to be clear and bright tomorrow"switch desc.lowercaseString as NSString {case let x where x.rangeOfString("clear").length != 0:    println("clear")case let x where x.rangeOfString("cloudy").length != 0:    println("cloudy")default:    println("no match")}// prints "clear"


Swift 5 Solution

func weatherImage(for identifier: String) -> UIImage? {    switch identifier {    case _ where identifier.contains("Clear"),         _ where identifier.contains("rain"):        return self.soleadoImage    case _ where identifier.contains("broken clouds"):        return self.nubladoImage    default: return nil    }}