Thiago Valente
Thiago Valente

Reputation: 703

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 )

Upvotes: 1

Views: 1152

Answers (2)

Fedy_
Fedy_

Reputation: 491

If value is optional just add ?

var name: String? = "Thiago Valente"

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

Upvotes: 0

Sweeper
Sweeper

Reputation: 273565

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.

Upvotes: 4

Related Questions