Saturday, June 28, 2014

if condition / switch case

Swift prevents any non-Boolean value in an if condition that requires a Bool.

let myCondition = 1
if myCondition {


let myCondition = 1
if myCondition == 1 {


let myCondition = true
if myCondition {


The switch case is as below:

var myCondition = 5 //Change this for different values

switch myCondition {
case 0:
    print("This is zero.")
case 1:
    print("myCondition is one.")
case 2,3:
    print("I like number two or three.")
case 4...10:
    print("Four to ten.\nfallthrough")
    print("The default case.")
    //print("Print more")

//Console output: myCondition is one.

//No "break" is required for each case.
//Default condition is essential.
//Use comma if the cases share the same codes, e.g. case 2, 3:
//Use ... to represent consecutive values
//Write fallthrough if the case below needs to be run.

//Change this:

let myCondition = 7

//Console output: 
Four to ten.
The default case.

//"Print more" is not printed because of the break.

IBM Swift Sandbox Example

No comments:

Post a Comment