Search code examples
switch-statementswift5

Swift - How do I check if switch case contains an value


I'm trying to do something like that

var name = "Thiago Valente"

switch name {
case .contains("Valente"):
   return "Hello, My surname is like your"
default:
   return "Hi ;)"
}

The contains don't exists, so it is possible to do with switch case? ( I know it's simple to do with if-else )


Solution

  • You can use the let x pattern, followed by a where clause:

    var name = "Thiago Valente"
    
    switch name {
    case let x where x.contains("Valente"):
       return "Hello, My surname is like your"
    default:
       return "Hi ;)"
    }
    

    Normally let x will match every value, but you say more specifically what kind of values you want to match in the where clause.