Chapter 2: Conditionals

Swift Programming from Scratch

The book is updated for Swift 3 and the Swift Sandbox is integrated, making the exercises interactive. Read more about the book here.

  1. First Steps
  2. Conditionals
  3. Types
  4. Loops
  5. Strings
  6. Arrays
  7. Functions
  8. Recursion
  9. Closures
  10. Tuples & Enums
  11. Dictionaries

?You can buy Training app  +  the PDF and ePub versions of the book!

    cover final small     +     cover final small
Buy now!

Chapter 2: Conditionals

 

 

 

Introduction

Sometimes you want to run some code only if some conditions are met. For example:

var numberOfOranges = 1
var numberOfApples = 5

if numberOfApples > numberOfOranges {
    print("You have more apples than oranges!")
}

You can compare numbers using these operators:

  • < Less than
  • <= Less than or equal
  • > Greater than
  • >= Greater than or equal
  • == Equal
  • != Not equal
1 != 2 // true
1 == 2 // false
1 < 2 // true
1 > 2 // false
1 <= 2 // true
3 >= 3 // true

Anatomy of an if statement

An if statement has the following form:

if CONDITION {
    STATEMENT
    STATEMENT
    ...
    STATEMENT   
}

The statements between curly braces ({}) will only be executed if the given condition is true! The statements that follow after the curly brace ends will be executed independently of the condition.

An if statement can also have an else branch:

if CONDITION {
    STATEMENT
    STATEMENT
    ...
    STATEMENT   
} else {
    STATEMENT
    STATEMENT
    ...
    STATEMENT
}

The statements in the else branch i.e. between else { and } will only be executed if the condition is false.

Consider the following code as an example:

var money = 20 // you have 20$
var burgerPrice = 10 // you ate a good burger

// if you have enough money pay for the burger
if money >=  burgerPrice {
    print("pay burger")
    money -= burgerPrice
} else {
// otherwise you will need to go wash dishes to pay for your meal
// hopefully this will not be the case
    print("wash dishes")
}

// if you have some money left order desert
if money > 0 {
    print("order desert")
}

Nesting conditions

If statements can be nested inside other if statements.

if CONDITION {
    STATEMENT

    if CONDITION2 {
        STATEMENT
        STATEMENT
        ...
        STATEMENT   
    }

    STATEMENT
    ...
    STATEMENT   
}

For example lets say we have two variables age and money. We’ll write some code to determine if you can buy a car that costs 20000. For this you’ll need at least 20000 money and at least an age of 18:

var age = 23
var money = 25000

if age >= 18 {
    if money >= 20000 {
        print("Getting a new car, baby!")
    } else {
        print("Sorry, you don't have enough money.")
    }
} else {
    print("Sorry, you're not old enough.")
}

Multiple conditions

Mutiple conditions can be chained together using the && (AND) operator and the || (OR) operator

The && (AND) operator is used to check if two conditions are simultaneously true. For example consider we have the age of a person stored in a variable age and want to determine if the person is a teenager (age is between 13 and 19). We have to check that the age is greater than or equal to 13 AND less than or equal to 19. This is accomplished by the code below:

var age = 18
if age >= 13 && age <= 19 {
    print("Teenager")
}

This is equivalent to the following code:

var age = 18
if age >= 13 {
    if age <= 19 {
        print("Teenager")
    }   
}

The || (OR) operator is used to check that at least one of two conditions is true.

Consider again that we have the age of a person stored in a variable age. We want to print a warning if the age is less than or equal to 0 OR the age is greater than or equal to 100. This is accomplished by the code below:

var age = 123
if age <= 0 || age >= 100 {
    print("Warning age is probably incorrect!")
}

Note: The OR in programming is not equivalent to the or in everyday language. If someone asks you if you want beef or chicken that means that you can have only one of two. In programming an or statement is also true when both conditions are true at the same time. For example:

var numberOfSisters = 1
var numberOfBrothers = 2

if numberOfSisters > 0 || numberOfBrothers > 0 {
    print("Has siblings")
}

To get a better understanding of how AND(&&) and OR(||) behave have a look at the truth tables below:

// AND
true && true // true
true && false // false
false && true // false
false && false // false

// OR
true || true // true
true || false // true
false || true // true
false || false // false

Negating a condition

You can negate a condition using the ! operator. A negated condition has oposite value to the original condition. i.e. if the initial condition was true than it’s negation is false. If the initial condition is false than it’s negation istrue.

For example if we wanted to check if an age is NOT the age of a teenager we could use the following code

var age = 18
if !(age >= 13 && age <= 19) {
    print("Not a teenager!")
}

Note:

if condition {
    // DO SOMETHING WHEN CONDITION IS TRUE
} else {
    // DO SOMETHING WHEN CONDITION IS FALSE
}

is equivalent of :

if !condition {
    // DO SOMETHING WHEN CONDITION IS FALSE
} else {
    // DO SOMETHING WHEN CONDITION IS TRUE
}

Note: If you have an if statement with an else branch than it’s not recommended to negate the condition.

The below table shows the values of negating some conditions:

!true // false
!false // true
!(true && true) // false
!(true || false) // false
!(false || false) // true

2.1 Max

You are given two numbers a and b print the largest one.

Example 1

Input:

var a = 11
var b = 22

Output:

22

[collapse]
Example 2

Input:

var a = 23 
var b = 12

Output:

23

[collapse]
Example 3

Input:

var a = 2 
var b = 4

Output:

4

[collapse]
Solution

var a = 11
var b = 23

if a > b {
    print(a)
} else {
    print(b)
}

[collapse]

2.2 Even or Odd

You are given a number. Print even if the number is even or odd otherwise.

Example 1

Input:

var number = 1

Output:

odd

[collapse]
Example 2

Input:

var number = 12

Output:

even

[collapse]
Hint

Use the remainder (%) operator to determine if the number is even or odd

[collapse]
Solution

let number = 2

if number % 2 == 0 {
    print("even")
} else {
    print("odd")
}

[collapse]

2.3 Divisibility

You are given two numbers a and b. Print "divisible" if a is divisible by b and "not divisible" otherwise.

Example 1

Input:

var a = 22
var b = 11

Output:

divisible

[collapse]
Example 2

Input:

var a = 12 
var b = 3

Output:

divisible

[collapse]
Example 3

Input:

var a = 12 
var b = 5

Output:

not divisible

[collapse]
Hint 1

Use the remainder (%) operator to check if b divides a.

[collapse]
Hint 2

To check if b divides a you need to check if the remainder of the division of a to b is 0.

[collapse]
Solution

var a = 12
var b = 3

if a % b == 0 {
    print("divisible")
} else {
    print("not divisible")
}

[collapse]

2.4 Two of the same

You are given three variables a, b and c. Check if at least two variables have the same value. If that is true printAt least two variables have the same value otherwise print All the values are different.

Example 1

Input:

var a = 1 
var b = 2  
var c = 3

Output:

All the values are different

[collapse]
Example 2

Input:

var a = 1 
var b = 2  
var c = 1

Output:

At least two variables have the same value

[collapse]
Example 3

Input:

var a = 3 
var b = 3  
var c = 3

Output:

At least two variables have the same value

[collapse]
Hint

Use the OR (||) operator to chain multiple equality checks

[collapse]
Solution

var a = 2
var b = 2
var c = 2

if (a == b) || (a == c) || (b == c) {
    print("At least two variables have the same value")
} else {
    print("All the values are different")
}

[collapse]

2.5 Breakfast

You are working on a smart-fridge. The smart-fridge knows how old the eggs and bacon in it are. You know that eggs spoil after 3 weeks (21 days) and bacon after one week (7 days).
Given baconAge and eggsAge(in days) determine if you can cook bacon and eggs or what ingredients you need to throw out.
If you can cook bacon and eggs print you can cook bacon and eggs.
If you need to throw out any ingredients for each one print a line with the text throw out <ingredient> (where <ingredient> is bacon or eggs) in any order.

Example 1

Input:

var baconAge = 3
var eggsAge = 2

Output:

you can cook bacon and eggs  

[collapse]
Example 2

Input:

var baconAge = 9
var eggsAge = 20

Output:

throw out bacon  

[collapse]
Example 3

Input:

var baconAge = 9
var eggsAge = 23

Output:

throw out bacon  
throw out eggs

[collapse]
Hint 1

Check for the case where you can cook bacon and eggs first.

[collapse]
Hint 2

In the else branch check the ingredients that need to be thrown out.

[collapse]
Solution

var baconAge = 6
var eggsAge = 12

if baconAge <= 7 && eggsAge <= 21 {
    // bacon and eggs are ok, we can cook
    print("you can cook bacon and eggs")
} else {
    // either eggs or bacon or both are spoiled
    if baconAge > 7 {
        print("throw out bacon")
    }
    if eggsAge > 21 {
        print("throw out eggs")
    }
}

[collapse]

2.6 Leap Year

You are given a year, determine if it’s a leap year. A leap year is a year containing an extra day. It has 366 daysinstead of the normal 365 days. The extra day is added in February, which has 29 days instead of the normal 28 days. Leap years occur every 4 years. 2012 was a leap year and 2016 will also be a leap year.
The above rule is valid except that every 100 years special rules apply. Years that are divisible by 100 are not leap years if they are not also divisible by 400. For example 1900 was not a leap year, but 2000 was. Print Leap year! or Not a leap year! depending on the case.

Example 1

Input:

var year = 2000

Output:

Leap year!

[collapse]
Example 2

Input:

var year = 2005

Output:

Not a leap year!

[collapse]
Example 3

Input:

var year = 1900

Output:

Not a leap year!

[collapse]
Example 4

Input:

var year = 1992

Output:

Leap year!

[collapse]
Hint

Use the remainder (%) operator to check for divisibility by 4. Don’t forget to check the special case when year is divisible by 100.

[collapse]
Solution

let year = 2014
if year % 4 == 0 {
    if year % 100 == 0 && year % 400 != 0 {
        print("Not a leap year!")
    } else {
        print("Leap year!")
    }
} else {
    print(year, terminator: "")
    print("Not a leap year!")
}

[collapse]

2.7 Coin toss

If you use random() it will give you a random number. Generate a random number and use it to simulate a coin toss. Print heads or tails.

Hint

Use the remainder operator (%) to check if the randomNumber is even(heads) or odd(tails).

[collapse]
Solution

import Foundation

var randomNumber = random()

if randomNumber % 2 == 0 {
    print("heads")
} else {
    print("tails")
}

[collapse]
Funny Solution

import Foundation

let randomNumber = random()

if randomNumber == 0 {
    print("it fell under the couch")
} else if (randomNumber % 2 == 0) {
    print("tails")
} else {
    print("head")
}

[collapse]

2.8 Min 4

You are given four variables a, b, c and d. Print the value of the smallest one.

Example 1

Input:

var a = 3 
var b = 5  
var c = 4 
var d = 2

Output:

2

[collapse]
Example 2

Input:

var a = 1 
var b = 3  
var c = 4 
var d = 2

Output:

1

[collapse]
Example 3

Input:

var a = 6 
var b = 7  
var c = 4 
var d = 5

Output:

4

[collapse]
Hint

Use a variable to hold the minimum value and initalize it with a. Assume that a is the smallest value. You’ll have to update the value in case a is not the smallest value.

[collapse]
Solution

var a = 5
var b = 6
var c = 3
var d = 4

var min = a

if b < min {
    min = b
}

if c < min {
    min = c
}

if d < min {
    min = d
}

print(min)

[collapse]

2.9 Testing

Test if number is divisible by 3, 5 and 7. For example 105 is divisible by 3, 5 and 7, but 120 is divisible only by 3 and 5 but not by 7. If number is divisible by 3, 5 and 7 print number is divisible by 3, 5 and 7otherwise print number is not divisible by 3, 5 and 7.

Example 1

Input:

var number = 60

Output:

number is not divisible by 3, 5 and 7  

[collapse]
Example 2

Input:

var number = 105

Output:

number is divisible by 3, 5 and 7  

[collapse]
Hint

Use the remainder (%) operator to check for divisibility.

[collapse]
Solution

let number = 210

if number % 3 == 0 && number % 5 == 0 && number % 7 == 0 {
    print("number is divisible by 3, 5 and 7")
} else {
    print("number is not divisible by 3, 5 and 7")
}

[collapse]

2.10 Point

Find out if the point (x, y) is inside of the rectangle with the lower-left corner in (lowX, lowY) and the upper-right in (highX, highY). Print inside or not inside depending on the case.

Example 1

Input:

var x = 1
var y = 2
var lowX = 1
var lowY = 1
var highX = 3
var highY = 3

Output:

"inside"

Point 1

[collapse]
Example 2

Input:

var x = 2
var y = 2
var lowX = 1
var lowY = 1
var highX = 3
var highY = 3

Output:

"inside"

Point 2

[collapse]
Example 3

Input:

var x = 4
var y = 4
var lowX = 0
var lowY = 0
var highX = 3
var highY = 5

Output:

"not inside"

Point 3

[collapse]
Hint

Chain multiple comparisons together using the AND (&&) operator.

[collapse]
Solution

var x = 1
var y = 2
var lowX = 1
var lowY = 1
var highX = 3
var highY = 3

if x >= lowX && y >= lowY && x <= highX && y <= highY {
    print("inside")
} else {
    print("not inside")
}

[collapse]

2.11 Hitpoints

You are working on a videogame where the character has a certain number of hitpoints(HP) ranging from 0 to 100.
100 represents full health
0 represents dead.
You want to add regenerating health to the game using the following rules:

  • HP always regenerates up to numbers of the form X0 (75 -> 80 , 32 -> 40 …)
  • When HP is below 20 it regenerates up to 20 (13 -> 20, 5 -> 20, …)
  • If the character has 0 HP then he doesn’t regenerate life (he’s dead)

Given the current hp of the character stored in a variable hp print the hp the player will have after regenerating life.

Example 1

Input:

var hp = 60

Output:

60

[collapse]
Example 2

Input:

var hp = 26

Output:

30  

[collapse]
Example 3

Input:

var hp = 12

Output:

20

[collapse]
Example 4

Input:

var hp = 4

Output:

20

[collapse]
Example 5

Input:

var hp = 95

Output:

100

[collapse]
Hint

Check for the case when hp is between 1 and 19 first

[collapse]
Hint

Discard the last digit of hp via division

[collapse]
Solution

var hp = 75

if hp > 0 && hp < 20 {
    hp = 20
} else if hp % 10 != 0 {
    hp = hp / 10
    hp = hp + 1
    hp = hp * 10
}

print(hp)

[collapse]

 

Swift Programming from Scratch

Read more about the book here.

  1. First Steps
  2. Conditionals
  3. Types
  4. Loops
  5. Strings
  6. Arrays
  7. Functions
  8. Recursion
  9. Closures
  10. Tuples & Enums
  11. Dictionaries

?You can buy Training app  +  the PDF and ePub versions of the book!

    cover final small     +     cover final small
Buy now!

 

Feel free to ask any questions in the comments bellow. :)

1 Star2 Stars3 Stars4 Stars5 Stars (4 votes, average: 4.25 out of 5)
Loading...

  23 comments for “Chapter 2: Conditionals

  1. Anath
    February 17, 2015 at 6:52 pm

    Hi again,
    These are another set of good problems, but I have found a discrepancy between what the site is having you do and the app.

    On problem 2.6 Leap year, the directions indicate you should print “Leap year!” or “Not a leap year!” as your solution. The code solution on the site is println(“Leap year!”)

    However this is not the same solution that the app will take, and it will actually reject the solution when copy and pasted from the site.

    The app wants you to “print the year followed by ‘is (not) a leap year'” which means the solution code for the app is be println(“\(year) is a leap year!”)

    I don’t recall seeing “\(variable)” yet in this series of exercises so having it show up in this problem may be confusing to new programmers.

    Thanks again for putting this together, its a lot of fun and very helpful. :)

    • February 17, 2015 at 9:45 pm

      We updated the content of the book after we updated the app. That’s the reason for the differences. We are really glad you like the exercises :)

  2. Sheriff
    March 5, 2015 at 12:14 am

    In example 2.11 I wrote the code as follows:
    var hp = 34
    var remainder = 10 – (hp % 10)

    if hp 0 {
    hp = 20
    } else if hp < 100 && hp % 10 !=0 {
    hp += remainder
    }
    println(hp)

    It seems like it works the same way, but is the guide version more efficient? I'm just curious. I love the guides btw.

    • March 5, 2015 at 10:15 am

      Both versions are good solutions. We considered the one from the book easier to understand.

  3. yann
    May 25, 2015 at 2:45 pm

    Hi I tried the 2.5 and I was thinking isn’t this faster ? the last “if” seams unnecessary to me but maybe I am wrong ?

    var baconAge = 6 // the bacon is 6 days old
    var eggsAge = 12 // eggs are 12 days old

    if (baconAge < 7) && (eggsAge 7) {
    println(“throw out bacon”)
    } else {
    println(“throw out eggs”)
    }
    }

    • May 27, 2015 at 8:46 am

      your solution does not work if both eggs and bacon have to be thrown.

  4. Chris
    July 13, 2015 at 10:23 pm

    Hi Andrei,

    First of all I would like to thank you for making this! I’m learning and making progress each day!

    Anyways in 6.2, I followed your solution but I still get incorrect outputs.
    Here is my code below:

    let year = 2014

    // your code here

    if year % 4 == 0 {

    if year % 100 == 0 && year % 400 != 0 {

    println(“\(year) is not a leap year!”)

    } else {

    println(“\(year) is a leap year!”)
    }

    } else {

    println(“\(year) is a leap year!”)
    }

    I’m pretty sure I miss something but I don’t know where and what. Hope you can help so I can proceed. Thanks! :D

    • Chris
      July 13, 2015 at 10:27 pm

      Nvm… I forgot “not”. This is what happens when I don’t have sleep. lol

  5. joe
    August 3, 2015 at 5:02 am

    is someone able to fill me in with “switch” “case” and “default”, the following code is unclear

    switch i {
    case 8:
    println(“it was 8”)
    case 10:
    println(“it was 10”)
    default: println(“it was none of the above”)
    }

  6. Selim
    September 25, 2015 at 2:07 am

    Since the swift 2 update I haven’t been getting a “Compilation Error” whenever I do a playground exercise. I know my code is correct because I even referenced it to the solution that’s provided. If there isn’t an easy solution, is there anyway I can possibly just skip the exercise? Thanks in advance.

    • September 25, 2015 at 8:00 am

      we are working on the update! :)
      it should be done by next week!

  7. T
    December 11, 2015 at 8:06 pm

    Hey Andrei,

    Just wan to say thanks so much for the book and the site. Its been a great help.

    Cheers

  8. Giacomo
    February 15, 2016 at 11:36 pm

    hey, in exercise 2.5 I can’t get my answer straight. I don’t know where my code is wrong.
    Here it is,
    var baconAge = 8 // the bacon is 6 days old
    var eggsAge = 22 // eggs are 12 days old

    // your code here

    if baconAge <= 7 {
    if eggsAge <= 21 {
    print("you can cook bacon and eggs")
    } else {
    print("throw out eggs")
    }
    }else {
    print("throw out bacon")
    }

    • February 19, 2016 at 1:00 pm

      You don’t handle the case where both are spoiled.

  9. taylor
    May 23, 2016 at 6:35 am

    Hey Andrei, could you explain the solution to 2.11? I don’t understand how the three hp statements for the “else if” condition produces the correct outputs for every case. Does hp run through all three statements, and if so wouldn’t hp = 75 output 85?

  10. Ray
    June 24, 2016 at 10:40 pm

    I don’t understand anything about the problem for 2.11. Would really like to get it solved though. Can you re-word it?

  11. Ray
    June 24, 2016 at 10:49 pm

    You can disregard my comment about 2.11. I was going off of the explanation in the app and not in the book.

  12. Ray
    June 25, 2016 at 12:43 am

    So I have been stuck on Leap Year all day. Here’s my test code:

    var year = 1900

    if year % 100 == 0 && year % 400 != 0 {
    print(“Not a leap year”)
    }

    else if year % 4 == 0 {
    print(“Leap year!”)
    }

    else if year % 4 != 0{
    print(“Not a leap year!”)
    }

    else {
    print(“”)
    }

    When I run it through the app, it says that 1900 is incorrect, but clearly it is. Am I missing something?

    Thx

    • Dennis
      July 22, 2016 at 7:18 am

      Ray, your first if statement only checks the condition “Years that are divisible by 100 are not leap years if they are not also divisible by 400.”

      If you read the text carefully, it says that a leap year usually occurs every four years, but only if that year follows the rule above. This means you need an if within an if statement to check that condition.

      Is the year divisible by 4?
      If yes, check if that same year is also divisible by 100, but not divisible by 400.
      If no, it’s not a leap year at all.

      Working code
      ——————
      let year = 2014
      if year % 4 == 0 {
      if year % 100 == 0 && year % 400 != 0 {
      print(“The year \(year) is not a leap year!”)
      } else {
      print(“The year \(year) is a leap year!”)
      }
      } else {
      print(“The year \(year) is not a leap year!”)
      }

  13. Var-Sum
    September 19, 2016 at 9:37 pm

    Hello. Great Great Tutorial. So Great that I’m trying to think and rethink all the exercises. This is the best way to learn.

    I have made an alternative solution for 2.11 exercise. Here it goes:

    var hp = 54

    if hp > 0 {
    if hp > 20 {
    if hp % 10 != 0 {hp += (10 – (hp % 10))
    } else {hp += 0}
    } else {hp = 20}
    } else {print(0)}

    let comment = “Your life is”
    print(comment,hp)

    • Var-Sum
      September 19, 2016 at 9:44 pm

      This is the right version, sorry:

      var hp = 0

      if hp > 0 {
      if hp > 20 {
      if hp % 10 != 0 {hp += (10 – (hp % 10))
      } else {hp += 0}
      } else {hp = 20}
      } else {hp = 0}

      let comment = “Your life is”
      print(comment,hp)

      Although if I copy and paste what is published it gives me error and I dont know why.

  14. John
    January 20, 2017 at 4:08 am

    Is this being updated, because I find some lines of code are being displayed as errors.

    • February 13, 2017 at 1:26 pm

      Yes, we are updating this resource. Where did you find errors?

Leave a Reply

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

Subscribe
We send about one email per week with our latest tutorials and updates
Never display this again :)