Swift switch tutorial with Example

Switch statement takes a value and compare it with different cases. If any case matches, it runs a block of code. It is like using multiple ‘if’ conditions and checking each of them one by one. A switch statement can be defined as below :

switch item {
case item1 :
    //item is equal to item1
case item2,item3 :
    //item is equal to item2 or item3
    .
    .
    .
default :
    //item is not equal to any values above
}

So, we will pass one ‘item’ to the case statement. It will check each of these ‘case’ statements one by one : if it matches to any case, code for that ‘case’ will run. If no case is matched, one ‘default’ case is defined at last. Following example will clarify your doubts :

let num: Int = 3

switch num {
case 1 :
    print ("One")
case 5 :
    print ("Five")
case 3 :
    print ("Three")
case 4 :
    print ("Four")
default :
    print ("Not found")
}

Here, num is equal to 3. First ‘case 1’ will run. Since 1 is not equal to 3, it will move to ‘case 5’ . Again 5 is not equal to 3 , it will move to ‘case 3’ . This time it will pass and run the statements defined inside ‘case 3’ i.e. all statements after ‘case 3’ and before ‘case 4’ will run. That means this program will print ‘Three’ . After that it will exit without checking other cases. On ‘C’ or ‘objective – c’, we need to use one ‘break’ statement to exit a case. But in swift the control exit automatically.

Handling multiple cases in swift switch statement :

If the result for multiple ‘case’ statement is same, we can combine them by separating each case statement by a comma ‘,’ . These types of cases are known as compound cases in swift. Example :

let character : Character = "b"

switch character{
case "a","A":
    print ("A")
case "B","b":
    print ("B")
default:
    print ("Not found")
}

Here, for ‘a’ or ‘A’ , the output is same . Similarly for ‘b’ or ‘B’, it will print the same result. We can also write compound cases over multiple lines as below :

switch character{
case "a",
      "A":
    print ("A")
case "B",
      "b":
    print ("B")
default:
    print ("Not found")
}

Interval matching in swift switch case :

We can write case with interval like ‘case low..<high’ which will true for all values starting from ‘low’ to ‘high-1’ . Take a look into the below example :

let msg : String = "The number is a "
let numberMsg : String
let number = 33

switch number{
case 0..<10:
    numberMsg = "one digit number"
case 10..<100:
    numberMsg = "two digit number"
case 100..<1000:
    numberMsg = "three digit number"
case 1000..<10000:
    numberMsg = "four digit number"
default :
    numberMsg = "more than four digit number"
}

print (msg+numberMsg)

It will print :

The number is a two digit number

First case will consider all numbers from 0 to 9. Second case will consider from 10 to 99. Since 33 lies in this range, it will print the above output.

Using switch case with tuples :

Tuples in swift is a comma separated list of values enclosed in parenthesis. We can use tuples with switch case in swift. We can check for a specific tuple value by comparing each elements or for an item, we can use a underscore (_) to match any value for that position. Example :

let point1 = (1,1)

switch point1 {
case (0,0):
    print ("The point is at the origin")
case (_,0):
    print ("The point is on X axis ")
case (0,_):
    print ("The point is on Y axis")
default :
    print ("The point is not on any axis")
}

Output :

The point is not on any axis

For (1,0), (2,0) etc, it will pass the second case. Becasuse “_” means any item will satisfy this number . Similarly the third case will pass for values like (0,2),(0,9) etc.

Tuples with interval in switch case :

We can even add range for both elements of a tuple . (min1…max1,min2…max2) will consider all points with first item from min1 to max1 range and second item from max1 to max2. For example :

let point2 = (-2,2)

switch point2{
case (0...2,0...2):
    print ("The point is on first area")
case (0...2,-2...0):
    print ("The point is on second area")
case (-2...0,-2...0):
    print ("The point is on third area")
case (-2...0,0 ... 2):
    print ("The point is on fourth area")
default :
    print ("The point is not inside the square")
}

In this example, the point is ‘(-2,2)’, it will only pass for ‘case (-2…0,0…2′ )’ . Because for this case, minimum value for the first element is -2 and maximum value is 0. For the second element, minimum value is 0 and maximum value is 2. ‘(-2,2)’ lies in this case .

Value binding in Swift switch cases :

Value binding means that a swich case can name one or multiple values using a constant or variable and can use it inside its body. Example :

let point3 = (0,5)

switch point3{
case (0,let y):
    print ("The point (0,\(y) ) is on Y Axis ")
case (let x, 0):
    print ("The point (\(x),0) is on X Axis")
default :
    print ("The point (\(x),\(y)) is not on any axis")
}

Output :

The point (0,5) is on Y Axis

Point (0,5) will pass the first case case (0 ,let y). Second value, i.e. 5 will be renamed to y using ‘let y’ statement and it can be used inside the body . Similarly case (let x, 0) renamed the first value to ‘x’.

Switch case with a where clause in swift :

We can check for conditions with a switch case using ‘where’ clause in swift. Check the example below :

let point4 = (10,10)

switch point4 {
case let (x,y) where x == y:
    print ("Both x and y coordinates are same for (\(x),\(y))")
default:
    print ("x and y coordinates are not same for (\(x),\(y))")
}

Output :

Both x and y coordinates are same for (10,10)

Here, the first switch condition will pass for all input with same first and second value. In our example (10,10), ‘let (x,y) where x == y’ condition first renamed both values to x,y (i.e. x= 10 and y= 10) and then it checked if ‘x == y’ or not. For our case, ’10 == 10′ , so the case condition is passed and first ‘print’ statement is executed.

That’s all for switch statement in swift. One thing we should remember that if multiple switch cases satisfy the condition for a value, only the first switch block will execute, others will be ignored.
If you love this article, drop a comment below and like our facebook page and subscribe for the weekly newsletter.

Sitewide-USD 336x280

Leave a Reply