Switch Statements in SwiftUI: How to Control the User Interface with Conditional Logic

Learn how to use switch statements in Swift

A switch statement listens to a variable x and executes some code depending on the value of x. 

The switch statement is best used when you have to deal with multiple cases and don't want to use and if/else statement. The skeleton of a switch statement in SwiftUI looks like this:

switch someVariableToEvaluate {
case someCaseA:
		// Do something
case someCaseB:
		// Do something else
case someCaseC:
		// Do something else
default:
		// Do something else
}

..

If you're familiar with the Javascript switch statement, then this is pretty much the same.

..

Example 

Let's take an example. We want to display a different greeting depending on the selected language. First, let's define a variable called language, which is a String and is initially set to French.

var language: String = "French"

..

Then, let's create our switch statement. It will display a text in the selected language.

switch language {
case "French":
		Text("Bonjour!")
case "Spanish":
		Text("Hola!")
case "Chinese":
		Text("你好!")
default:
		Text("Hello!")
}

..

And there you have it! Since the initial language is set to French, the text displayed on the screen will be Bonjour!. 

If we change it to any other language in the switch statement, it will change to the corresponding text. 

If the value of language is not a case in the switch statement, it will return by default Hello!.

..

Comments