Swift

Conditionals

Evaluating conditions with booleans

What is the Control Flow?

Control flow is basically the decision-making that goes on in your program. If one thing is true, do this, if not, do that. This is a central concept to programming. When programming robots to make decisions on their own, we use this concept to let robots decide which path to take on their own, based on information gathered from encoders and other sensors. In addition, to decision-making, control flow involves looping through a section repeatedly until a condition is met.

Such concepts also come in handy with autonomous robots. But, on top of that, you can use such control flow concepts for basic tasks like controlling a lamp, or more advanced ones like matching english words to spoken words in new virtual assistant technology like Apple’s Siri or Microsoft’s Cortana.

How to use an if statement

An if statement checks if the conditions are true or false, then does something different. In this example, we will use the equality operator == which checks if two things are the same. We can compare a variety of things.

var a = 5
if a == 5 {
    print("A is equal to 5!")
}
    
var word = "violet"
if word == "violet" {
    print("The color is violet!")
}

We can also check if values are greater than or less than. This example also shows how the else statement works. If the condition is false, it leads into the else.

var b = 5
if b < 10 {
    print("\(b) is less than 10!")
} else {
    print("\(b) is not less than 10!")
}
    
// other in equality operators include >, >=, <=

Else If

We can consider multiple conditions as well. Else If statements come right after the if, and we can have as many as possible.

var number = 18
if number > 20 {
    print("\(number) is greater than 20!")
} else if number == 20 {
    print("\(number) is 20!")
} else {
    print("\(number) is less than 20!")
}

Multiple Conditions

We can also compare multiple conditions to make a final decision. && means and, and || means or. With &&, both need to be true, and with || only one needs to be.

var earthSpin = true
var worldUpsideDown = false
if !earthSpin && worldUpsideDown { // just writing the variable (if boolean) checks if true
    print("World broken!")
} else if earthSpin && !worldUpSideDown { // ! means to see if false is true
    print("World all good!")
}

if !earthSpin || worldUpSideDown {
    print("World is sort of good")
}
chevron_up