While the rest of the answers are probably correct so that if best way, you can do something similar using heroic abuse of the ~= operator:
import Foundation struct Substring { let substr: String init(_ substr: String) { self.substr = substr } } func ~=(substr: Substring, str: String) -> Bool { return str.rangeOfString(substr.substr) != nil } let input = "contains wat" switch input { case Substring("lol"), Substring("wat"): println("huh?") // this one is picked case Substring("dw"): println("dw") // you can also mix and match case "Explicit full string": println("matches whole string") default: println("Default") }
Switch statements in Swift can be extended by overloading the ~= operator. So, for example, the reason this works:
switch 2.5 { case 0...5: println("between nought and five") default: println("not in range") }
lies in the fact that there is a definition of the ~= operator that matches any Comparable type for the interval:
func ~=<I : IntervalType>(pattern: I, value: I.Bound) -> Bool
Here, by creating a new type of Substring , I created a way to match strings to substrings.
In theory, you can skip creating a Substring type and do the following:
func ~=(substr: String, str: String) -> Bool { return str.rangeOfString(str) != nil } let input = "contains lol" switch input { case "lol": println("lol") case "dw": println("dw") default: println("Default") }
This will work, but it will be a bad idea, because now you change the way you work with strings, universal so that partial matches are always true, which can lead to unpleasant and unexpected behavior elsewhere in your code.
source share