Collections and Control Flow - Conditional Statements

Next - and final - part of Control Flow is all to do with 'conditionals'. This will be linked to 'if' statements. These are a vital part of Swift and hopefully I'll be able to remember some! After that, the course is complete, which means I can crack on with 'functions' next...!

If Statements

var temperature = 22

if temperature < 18 {
    
    print("Wear a light sweater")
    
} else {
    
    print("No need for a sweater!")

}

A very simple example! I remembered the 'else' clause. This is when the statements evaluate to 'false'.  In the above example, the code runs through to the 'else'/false statement and prints the second line ("No need..."). However, if I made the the temperature higher than 18, then the other statement would.

The other aspect of this is using 'else if', which means another condition! 

var temperature = 22

if temperature < 18 {
    
    print("Wear a light sweater")
    
} else if temperature < 9 {
    
    print("Getting really cold now!")
    
} else {
    
    print("No need for a sweater!")
}

So I have added in the 'else if' - this is another clause. I can add multiple ones of these in. Now the issue here is that it is true for BOTH the first and second clauses! One solution is to put these in a logical order e.g. numbers from smallest to largest (the second clause swapped with the first). 

Another solution is to put in a range of values I'm assuming/using the && or ||! This will be looked at next. 

Logical Operators

The && symbols are used for 'and'. In other words, if two expressions are true. 

if temperature > 9 && temperature < 18 {
    
    print("Might want to wear a scarf my friend!")
}

So this indeed shows a range of temperatures, using the && symbols. 

var isRaining = true

var isSnowing = false

if isRaining || isSnowing {
    
    print("You need to wear welly boots!")
}

This is a good example of using the | | (the 'OR' symbols). The ones above are booleans - they can be used directly as an expression - no greater than/less than or equal to etc. 


The other operator is the not operator. Using ! before it means NOT!

if !isRaining {
    
    print("Yes - the sun is now out!")
    
}

This is better than writing isRaining == false. If a false is encountered in an AND expression, it won't even need to check the other one!

if (isRaining || isSnowing) && temperature < 3 {
    
    print("You will need gloves for sure!")
}

This is a good example of how to put multiple expressions, with the use of parenthesises for the or statements. For the or ones, the code only needs to check if ONE of those is true, then it is true!

var results: [Int] = []

for n in 1...100 {
    // Enter your code below
    if n % 2 != 0 && n % 7 == 0 {
        
        results.append(n)
        // End code
    }

}

Above was the challenge and I nailed it! I got the append bit wrong initially but got it sorted in the end! All good up to this point!

Switch Statements

From what I remember, this was another conditional but with a few changes in syntax...


var value = 4

switch value {
    
case 0...10:
    print("10 or less")
    
case 11...20:
    print("Between 11 and 20")
    
case 21...100:
    print("21 up to 100")
    
default:
    print("Your number is too high!")
    
}

Here is one I've done without any help at all! I remember that you must have a default, otherwise the code will not run. The syntax of case, colons etc. is very specific! 

var gameOfThronesNames = ["Tywin", "Daenerys", "Tyrion", "Jon", "Cersei", "Jaime"]

switch "Tywin" {
    
case "Tywin":
    
    print("Tywin Lannister is a powerful man")
    
case "Daenerys":
    
    print("Dany Targyeryn - the future ruler of Westeros!")
    
case "Tyrion":
    
    print("Tyrion will be Hand of the Queen")
    
default:
    
    print("We do not need that character right now")
    
    
}

It can also be done for items in an array. In the above example, I've switched "Tywin", so the first message will be printed. If I change that to Dany or Tyrion, their messages will be. For anyone else, then the default/last message will be used. 

Now, one clunky thing about the above is using the String of "Tywin", rather than using the index in the array. So replacing the "Tywin" after 'switch' with gameOfThronesNames[0] makes more sense!

There's an excellent tip here; add in the following before switch and change what we are switching...

for name in gameOfThronesNames {
    
switch name {

This means that EVERY item in the array is iterated over so everything is done! Clever! 

The Power of Switching

The question Pasan asks is why not use an if statement instead? Well something he includes is a list of values with commas, so I could have several characters for the same string printed basically. 

import GameKit

let randomTemp = GKRandomSource.sharedRandom().nextInt(upperBound: 50)

switch randomTemp {
    
case 0..<6: print("Freezing!")
    
case 6..<12: print("Quite cold")
    
case 12..<17: print("A bit chilly")
    
case 17..<23: print("Quite warm!")
    
case 23..<29: print("Hot and sunny!")
    
case 29..<36: print("Very hot!")
    
default: print ("Head in an oven!")
    
    
}

In this example, the half-open range is used - I guess in case there are decimals! I've changed Pasan's examples in terms of the numbers (celsius) and the text options. But the ideas is the same! 

So that's all of Conditional Statements! I really feel much more confident with these now, so well worth going through! Tomorrow: functions!

Comments

Popular posts from this blog

*Xcode Project Entry 2* F1 Quiz - part 1

Angela Yu Course Part 10 (up to lesson 112)

Angela Yu Xcode 12 Course - Part 7 (lectures 74 to 79)