Friday, September 11, 2015

Switch-Case in SWIFT 2.0

There have been major changes with switch...case conditions in SWIFT. With each version upgrade, things have gotten better and is at best in 2.0. Here are some simple samples of how SWITCH statements can be used

// Switch statement varieties in SWIFT 2.0
/*
* Switch statement with string and string conditions in cases
*/
let vegetable = "Baby  cucumber"
switch vegetable {
    case "celery":
        let vegetablecomment = "Add some rasinis, it will tase good"
    case "cucumber", "watercress":
        let vegetablecomment = "That would make a good tea sandwich"
    case let x where x.hasSuffix("pepper"):
        let vegetablecomment = "Is it spicy?"
    case let x where x.hasPrefix("Baby"):
        let vegetableComment = "mmmmmm, yummy..."
    default:
        let vegetablecomment="Not really"
}

/*
* Where clause makes it easy to process switch
*/
let myCirclePoint = (1, -1)
switch myCirclePoint {
case let(x, y) where x == y:
    print("It's a dot")
case let(x, y) where x == -y:
    print("It's a line towards left")
case let(x,y):
    print("Some arbitrary point in circle")
}

/*
* Switch statement with ranges in cases
*/
let numberCount = 100
switch numberCount {
case 1...99:
    print("Value less than 100")
case 100...199:
    print("Value less than 200")
default:
    print("Others")
}

/*
* Switch statement with tuples cases and ranges
* Isn't this awesome? Switch cases have never made code more easy.
* This makes code like error handlong so much more easy!!!
*/
let myHeight = (6, 11)
switch myHeight {
case (4, 1...11):
    print("Shortest")
case (5, 1...11):
    print("Tall")
case (6, _):
    print("Really tall")
case (_, 1...11):
    print("Are you human?")
default:
    print("Never executed, wish could get rid of it....")
}
}

No comments: