Swift - Control Flows

Control Flow


This is Part 3 of our Swift tutorial series. In this article, we are going to discuss about if and switch to make conditional execution and for, for-in, while and repeat-while to make loops.


IF

An If condition must contain a Boolean expression.


let inviteAllowed = true


if inviteAllowed {


print("All are welcome")


}


Swift allows developers to use let command work with If statement.


let guestName : String? = "Host"


if let guest = guestName {


print("Welcome,  \(guest)")


}


If guestName is set to nil, the if condition would be skipped


IF-ELSE

This is an extended version of If statement. When the condition is success, executes a set of command.
When the condition fails, execute another set of command.


let inviteAllowed = true


if inviteAllowed {


print("All are welcome")


}
else {


print("Invite Only")


}

SWITCH

Switch support all kind of data and operators in swift.


let favouriteColor = "light blue"


let statemnt = "My favourite colour is"


switch (favouriteColor) {
case "red":
print("\(statemnt) red")


case "blue":
print("\(statemnt) blue")


case let colour where colour.hasSuffix("blue"):
print ("\(statemnt) light blue")


default:
print("I like all colours")
}


FOR

A traditional for loop statement in all languages has
-Variable initialisation
-Check for condition
-Increment or decrement the variable


In swift, the traditional statement can be written in simpler format


for var count in 0..10 {


print (count)


}


0..10 - count values would be 0-9. 10 in not included.
to include 10, use 3 dots.


0...10 - count values would be 0-10


WHILE

Executes a set of commands till a condition is met


var n = 2


while n < 50 {


 n = n*2


}

Comments

Popular posts from this blog

Swift - Strings

What's new in Swift 4!

Swift - Classes