TagTuples

Swift – Switch cases

 

Firstly, in Swift, you no longer need to add break statement like other conventional programming languages like C. The other use of break was that if you don’t call break, it will automatically execute other cases too. For this purpose, we have fallthrough method that makes the next cases to be executed even if the current case succeeds. Let us now look at some examples.

Simple Switch case example

let a = 10
switch (a){
case 1:
println("Hello")
case 10:
println("World")
default:
println("Nothing")
}

Output

World

Another important thing to note is that, cases should be exhaustive and hence we should add a default case to make it exhaustive. The default case should have at least one statement. The one statement could be even break if you don’t need to do any other stuff.

Switch Ranges example

let a = 4
switch (a){
case 1...10:
println("Hello")
default:
break
}

Output

Hello

In the above example refers to range 1 to 10 with both 1 and 10 included.

Switch with fallthrough example

let a = 4
switch (a){
case 1...10:
println("One to ten")
fallthrough
case 5...10:
println("five to ten")
default:
break
}

Output

One to ten
five to ten

As you can see in the above example, fallthrough enable all the subsequent cases to be executed. You may need to use break in case you want to break in one of the cases while using fallthrough.

Simple tuples example

let a = ("raj", 10)
switch (a){
case ("raj",10):
println("Raj")
case ("john",20):
println("John")
default:
break
}

Output

Raj

Tuples enables us to pass multiple values and it is supported in switch case as well. In the above example, we have used a simple string and number comparison.
 

Tuples in Swift for multiple return values

 

Tuples are a great addition to Swift. It provides the ability for functions to return multiple values. In Objective-C and other languages, we need to use either custom objects or array of objects to return multiple values. Tuples helps us overcome this.

Syntax

func functionName(parameters with types)->(return values with types)

Example

func mathOperations(number1:Int ,number2:Int)->(add:Int ,sub:Int, mul:Int, div:Int )
{
return (number1+number2, number1-number2, number1*number2, number1/number2)
}

Calling a function

var a:(Int ,Int, Int, Int ) = mathOperations(1,number2: 2)
println("\(a.0)\(a.1)\(a.2)\(a.3)") 

Output

3 -1 2 0