Control Flow In Swift

Control Flow in Swift

If you don’t know about the swift basic check the swift tour. Let’s get the idea of Control flow in swift. Use if and switch to create conditionals, and use for-in, for, while, and repeat-while to create loops. Parentheses around the condition or loop variable are optional. Braces around the body are needed.

Control Flow in Swift : Swift Conditionals Statements

let individualScores = [75, 43, 103, 87, 12]
var teamScore = 0
for score in individualScores {
    if score > 50 {
        teamScore += 3
    } else {
        teamScore += 1

In an if statement, the conditional should be a Boolean expression—this means code like if score {…} is an error, not an implicit comparison to zero.

You can use if and let along to work with values which may be missing. These values are described as optionals. an optional value either contains a value or contains nil to point that a value is missing. Write a question mark (?) after the type of a value to mark the value as optional.

var optionalString: String? = "Hello"
print(optionalString == nil)
var optionalName: String? = "John Appleseed"
var greeting = "Hello!"
if let name = optionalName {
    greeting = "Hello, (name)"

If the optional value is nil, the conditional is false and therefore the code in braces is skipped. Otherwise, the optional value is unwrapped and assigned to the constant after let, which makes the unwrapped value available within the block of code.

Another way to handle optional values is to provide a default value using the ?? operator. If the optional value is missing, the default value is used instead.

let nickName: String? = nil
let fullName: String = "John Appleseed"
let informalGreeting = "Hi (nickName ?? fullName)"

Switches support any kind of data and a wide variety of comparison operations—they aren’t restricted to integers and tests for equality.

let vegetable = "red pepper"
switch vegetable {
case "celery":
    print("Add some raisins and make ants on a log.")
case "cucumber", "watercress":
    print("That would make a good tea sandwich.")
case let x where x.hasSuffix("pepper"):
    print("Is it a spicy (x)?")
    print("Everything tastes good in soup.")

Notice however let is utilized in a pattern to assign the value that matched that a part of a pattern to a constant.

After executing the code within the switch case that matched, the program exits from the switch statement. Execution doesn’t continue to the following case, thus there’s no need to explicitly break out of the switch at the end of every case’s code.

Control Flow in Swift : Loops In Swift

You use for-in to iterate over items in a dictionary by providing a pair of names to use for each key-value pair. Dictionaries area unit an unordered collection, thus their keys and values area unit iterated over in an absolute order.

let interestingNumbers = [
    "Prime": [2, 3, 5, 7, 11, 13],
    "Fibonacci": [1, 1, 2, 3, 5, 8],
    "Square": [1, 4, 9, 16, 25],
var largest = 0
for (kind, numbers) in interestingNumbers {
    for number in numbers {
        if number > largest {
            largest = number

Use while to repeat a block of code until a condition changes. The condition of a loop can be at the end instead, ensuring that the loop is run at least once.

var n = 2
while n < 100 {
    n = n * 2
var m = 2
repeat {
    m = m * 2
} while m < 100

You can keep an index in a loop—either by using ..<  to make a range of indexes or by writing an explicit initialization, condition, and increment. These two loops do the same thing:

var firstForLoop = 0
for i in 0..<4 {
    firstForLoop += i
var secondForLoop = 0
for var i = 0; i < 4; ++i {
    secondForLoop += i

Use ..< to make a range that omits its upper value, and uses  to make a range that includes both values.

for i in 1...5 {

I hope you will find this post very useful regarding control flow in swift. Let me know if you have any question regarding swift in a comment. I will reply to you ASAP.

Have you got a cool idea about iPhone App Development? Contact us Now to get a free consultation on your idea. Alphanso Tech is rated as one of the best iPhone App Development Company in India.

Post by Milan Sanathara

I am iOS Application Developer with an aspiration of learning new technology and creating a bright future in Information Technology.

Leave a Reply

Your email address will not be published. Required fields are marked *