Control Flow

Switch Case in Swift

A switch case is used test variable equality for a list of values, where each value is a case. When the variable is equal to one of the cases, the statements following the case are executed.

In Swift, a switch case can contain a temporary let constant, which contains the variable's value. This let constant can be used in a booleanExpression, which if true, will evaluate statements


Syntax
switch variable { 
    //checking for value
    case valueOne: 
        //statements 
    case valueTwo: 
        //statements
    //using the let
    case let variableValue where booleanExpression:
        //statements
    default: //executes if none of the above occur
        //statements
}

Notes

With a switch statement, the program goes through the conditions from top to bottom. If a condition is met, it executes the code and exits the block after. A fallthrough statement can be used other conditions need to be checked, even if a condition passes.

The switch statement can be used on strings, objects, and primitives.


Example
var choice = 'Y'
switch choice { 
    case 'Y': 
        print "Yes" 
    case 'N' : 
        print "No"
    case let choiceValue where choiceValue == 'M':
        print "It's a yes or no question, no maybe."  
    default: 
        print "Not a valid response"
}

< If Statement   |   For In Loop >

© 2019 SyntaxDB. All Rights Reserved.