Add



Swift Conditional Statements

There are 2 kinds of conditional statements in Swift programming language. One is If statement while the other is switch statement. In Swift, while writing switch statement, you do not need to place break statement at the end of each case as there is no implicit fall through in it which means it only executes matched case’s statements and comes out of switch.

If Statement

It is to execute the block of statements if condition is true.

    let myNum = 3
    if myNum>2
    {
	    print ("If block of statements are executed.")
    }

If-Else Statement

If-Else statement is to check the if statement’s condition. If true then execute if’s block of statements, otherwise execute else’s block of statements.

    let myNum = 3
    if myNum>2
    {
    	print ("If block of statements are executed.")
    }
    else
    {
	    print ("Else block of statements are executed.")
    }

If-Else If- Else Statement

If statement is to check the condition and execute the certain block where condition matches.

    let myNum = 3
    if myNum>10
    {
	    print ("If block of statements are executed.")
    }
    else if myNum==3
    {
	    print ("First Else-If block of statements are executed.")
    }
    else if myNum !=3
    {
	    print ("Second Else-If block of statements are executed.")
    }
    else
    {
	    print ("Else block of statements are executed.")
    }

Switch Statement

A switch statement takes a value and compares it against different cases. In switch statement, there is no need to write break statement in cases because there is no implicit fall through but if some case has only comment as block of statement then for that particular case you will have to write break statement. You cannot just write comments in any case of switch statement in Swift.

    let valueToCheck = "London"
    switch valueToCheck
    {
	    case "Paris":
    	    print("Your country is France")
	    case "London",
     		"Leeds":
    	    print("Your country is Italy")
	    case let x where x.hasSuffix("lin"):
		    print("Your location is \(x)")
	    default:
    		print("Unknown country")
    }

You can do value binding using switch statement. Like in the example there is case "case let x where x.hasSuffix("lin")". Now for example Berlin comes in to be checked by Switch statement then the x will be populated with Berlin as it has a suffix "lin" in it. Note that in this statement "where" clause has been used so it can be used with many kinds of things.

You can also give ranges in cases like case 1..<100 etc. Moreover, tuples can be checked in switch statement.