Conditional Statements in Swift

Conditional Statements:

It is often useful to execute different pieces of code based on certain conditions. You might want to run an extra piece of code when an error occurs, or to display a message when a value becomes too high or too low. To do this, you make parts of your code conditional.

Types of Conditional Statements in Swift:

Swift provides two ways to add conditional branches to your code.

  • If Statement
  • Switch Statement

1. If Statement:

In its simplest form, the if statement has a single if condition. It executes a set of statements only if that condition is true.

var temp = 30
if temp<=32{ print("It's very cold!") }

2. Switch Statement:

A switch statement considers a value and compare it against several possible matching pattern. It often executes an appropriate block of code, based on the first pattern that matches successfully. These statement provides an alternative to the if statement for responding to multiple potential states.

switch some value to consider{
case value 1:
respond to value 1
case value 2,
value 3:
respond to value 2 or 3
otherwise, do something else