Monday, October 5, 2015

Essentials of Swift - Learning Part II

Control Flow: 

There are two types of control flow statements 

1. Conditional Statements => e.g If and switch 
2. Loops => e.g. for-in and while 

let number = 10

if number < 10 
{
print (number is less than 10)
}
else if number > 100
{
print (number is greater than 100)
}
else 
{
print(“number is between 10 and 100 ”)
}

We can use optional binding in an if statement to check whether an optional contains a value. 

var optionalName:String ? = “Test”

if let tempStr = optionalName 
{
print “optional name is \(tempStr)”
}

if optional value is nil, the condition becomes false and won’t execute. 

We can use single if statement to bind multiple values. A where clause can be added to a case to further scope the conditional statement. In this case, if statement executes only if binding is successful for all of these values and all conditions are met. 

let optionalHello : “hello” 

let hello = optionalHello where hello.hasPrefix(“H”), let name = optionalName 
{
greeting = “\(hello), \(name)”
}

Switches are powerful, A switch statement can support any kind of data type and a wide range of comparison operations - it isn’t limited to integers and test for equality. 

let vegetable = “red pepper”

switch vegetable 
{
case “celery” : 
let vegetableComment = “Add some raisins and make ants on the log”
case “cucumber”, “watercress”:
let vegetableComment = “That would make good tea sanwitch”
case let x where x.hasPrefix(“bell”):
let vegetableComment = “Is it spicy \(x)?”
default:
let vegetableComment = “Everything tastes good in tea”
}

Notice that we don’t need to have a break here! 

References:

No comments:

Post a Comment