Conditional Statements & Operators

Free iOS Development Tutorial

This exercise is excerpted from Noble Desktop’s past app development training materials and is compatible with iOS updates through 2021. To learn current skills in web development, check out our coding bootcamps in NYC and live online.

Note: These materials are provided to give prospective students a sense of how we structure our class exercises and supplementary materials. During the course, you will get access to the accompanying class files, live instructor demonstrations, and hands-on instruction.

Topics covered in this iOS Development tutorial:

Conditional statements, Comparison operators, Arithmetic operators, Logical operators, Switch statements

Exercise Overview

In this exercise, you will learn about using conditional logic that tests a condition, then executes something, based on the outcome of that condition. You will also learn about various kinds of operators (arithmetic, comparison, and logical) and how they are used to test conditions.

Getting Started

  1. Launch Xcode if it isn’t already open.

  2. If you completed the previous exercise, Variables.playground should still be open. If you closed it, re-open it now.

  3. We suggest you complete the previous exercise (1C) before doing this one. If you did not do the previous exercise, complete the following:

    • Go to File > Open.
    • Navigate to Desktop > Class Files > yourname-iOS App Dev 1 Class and double–click on Swift Basics Ready for Conditionals.playground.

Conditional Statements

Basically what you’re doing when programming is testing conditions. For example, when you launch the Netflix app, it asks you to log in and then tests if the username and password you submitted matches the values in its database using a series of if statements. Programming is based largely on conditional logic, where you test a condition, then execute something based on the outcome of that condition.

  1. Let’s write an if statement. The syntax for an if statement starts with if followed by the condition you want to test, and then a set of curly braces ({}). Inside the curly braces is where you give a command to be executed if the condition is true. At the bottom of Xcode, add the bold code as shown below:

    if numberOfVerses == 4 {
       print("Yes the number of verses is 4")
    }
    

    Here, you are testing if the constant numberofVerses value is equal to 4, using a comparison operator (==). We’ll take a closer look at comparison operators later in this exercise.

  2. Let’s try another if statement with a boolean. At the bottom add:

    if iAmInHere == true {
       print("Yes I am in here")
    }
    

    Earlier in your code, you set iAmInHere to true. Because it is true, the line Yes I am in here prints. Booleans are an interesting case when used with a comparison operator. We’ll look at this in more depth later in the exercise.

  3. Let’s see what happens if the statement becomes false. Go back to the iAmInHere declaration (in the middle of the code) and change true to false:

    var iAmInHere = false
    
  4. On the right, notice that the statement (Yes I am in here) disappears because it is no longer true. An if statement will only execute if it is true.

  5. Go ahead and change false back to true.

  6. There may be times where you want to specify an action to take place if a statement is not true. For this, you can use an if/else statement. At the bottom, add a new if statement:

    if numberOfVerses == 5 {
       print("It is equal to 5")
    }
    
  7. Now add the condition that will happen if it’s not true:

    if numberOfVerses == 5 {
       print("It is equal to 5")
    } else {
       print("No it is not equal to 5")
    }
    
  8. Because this if statement is not true, it runs the else portion and prints: No it is not equal to 5

  9. You can also test multiple conditions and not execute either of them if both are false. For this you can use an else/if statement. At the bottom, type:

    if numberOfVerses == 5 {
       print("It is equal to 5")
    } else if numberOfVerses == 3 {
       print("It is equal to 3")
    }
    

    Since earlier you set numberOfVerses to equal 4, both of the conditions you just added will be false, so neither of the print commands are executed.

  10. Edit the code you just added to make the else/if statement true:

    if numberOfVerses == 5 {
       print("It is equal to 5")
    } else if numberOfVerses == 4 {
       print("It is equal to 4")
    }
    
  11. Look on the right to see: It is equal to 4

Comparison Operators

Operators are symbols or phrases used to check, change, or combine values. Comparison operators are naturally used to compare things. You can use the following comparison operators:

Operator Meaning
== Equal to
!= Not equal to
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to
  1. Let’s start with the greater than operator. At the bottom, type:

    if numberOfVerses > 3 {
       print("Yes there are more than 3 verses")
    }
    

    This is true so you will see the message appear on the right.

  2. Copy the greater than if statement you just typed and paste it directly below.
  3. Modify the copy as shown to make it a less than operator:
    if numberOfVerses < 10 {
       print("Yes there are less than 10 verses")
    }
    

    You should see it print out on the right because it is true.

  4. Again, paste a copy of the if statement at the bottom, then edit it to change it to a not equal to operator:
    if numberOfVerses != 5 {
       print("No this song does not have 5 verses")
    }
    

    It is true that numberOfVerses is not equal to 5, so it prints.

  5. Booleans are a little unique compared to other values because they can only ever be true or false. Earlier in this exercise, you wrote a conditional for the iAmInHere variable. Scroll up to find the following if statement:

    if iAmInHere == true {
       print("Yes I am in here")
    }
    
  6. With boolean values it’s redundant to ask if the variable is equal to true. You don’t need the extra code so go ahead and delete the comparison operator so that your code looks as follows:

    if iAmInHere {
       print("Yes I am in here")
    }
    
  7. To check if a boolean is false, you add the not operator, which indicates that the boolean is not true. At the bottom of Xcode, add:

    if !iAmInHere {
       print("No I am not in here")
    }
    

    This is saying if iAmInHere is false, then execute the statement.

    NOTE: The not operator is one of the logical operators. We’ll explore those shortly.

  8. Notice it is not printing out. Scroll up to find the following var statement.

    var iAmInHere = true
    
  9. Change true to false:

    var iAmInHere = false
    

    At the bottom right, it will display the print message.

  10. At the bottom of Xcode in the last conditional statement, delete the not operator before iAmInHere so that you end up with:

    if iAmInHere {
    

    The print message disappears because now the statement is asking if iAmInHere is true, but it is currently set to false.

  11. Go ahead and put the not operator back:

    if !iAmInHere {
    

Arithmetic Operators

You’ll often find yourself needing to do math in your programs. You can use arithmetic operators to perform simple calculations with variables.

You can use the following arithmetic operators:

Operator Use
+ Addition
- Subtraction
/ Division
* Multiplication
  1. Let’s create a couple variables that you can play with. At the bottom of your Playground, add the following bold code:

    var songsInSetList = 18
    var totalSongsPlayed: Int
    

    Remember that we need to include the data type since we have not assigned a value to the totalSongsPlayed variable yet.

  2. At a show, a band got called back for an encore and played three more songs than what was on their set list. Let’s write this statement programmatically using the addition operator. Add the following bold code:

    totalSongsPlayed: Int
    
    totalSongsPlayed = songsInSetList + 3
    
  3. Add the following to see what the totalSongsPlayed variable is now equal to:

    totalSongsPlayed = songsInSetList + 3
    print("They played \(totalSongsPlayed) songs!")
    

    On the right side, you should see the following new line: They played 21 songs!

  4. In another gig, the band had to cut their set list short and didn’t get a chance to play the last four songs. Add the following bold code after the last print statement to calculate the new totalSongsPlayed using the subtraction operator:
    totalSongsPlayed = songsInSetList - 4
    print("They only played \(totalSongsPlayed) songs...")
    

    Look on the right to see the following new line: They only played 14 songs…

  5. You can also multiply and divide variables. Let’s calculate how much money the band made from their gig, and how much each member got paid. Add the following variables after the last print statement:

    var ticketPrice = 20
    var peopleAttended = 100
    var bandMembers = 4
    
  6. To calculate how much money the band made, multiply the ticketPrice and peopleAttended variables. Add the following bold code:

    var moneyMade = ticketPrice * peopleAttended
    print("The band made $\(moneyMade).")
    
  7. On the right you should see the following new line: The band made $2000.

  8. Now that you know how much the band made, let’s see what each members cut was using some division. After the last print statement, add the following bold code:
    var membersCut = moneyMade / bandMembers
    print("Each member got a $\(membersCut) cut from the gig.")
    
  9. You should see the following new line: Each member got a $500 cut from the gig.

    NOTE: Arithmetic operators can be combined into compound calculations. These calculations follow standard mathematic order of operations or precedence. You can use parentheses to group parts of an expression.

Logical Operators

Not (!) operators are technically logical operators (rather than comparison operators). You can use the following logical operators:

Operator Meaning
! Not (inverse)
&& And (conjunction)
|| Or (disjunction)

There may be times when you want to test that two conditions are both true. The and operator would be good for this.

  1. At the bottom, type:
    if numberOfVerses == 4 && songRating > 3 {
       print("Yes this is a good song")
    }
    

    This says if numberOfVerses is equal to 4 AND songRating is greater than 3, then run the print function. Both conditions need to be true in order for this to execute.

    Since both conditions are true, the line prints.

  2. Try changing numberOfVerses from 4 to 5.

    if numberOfVerses == 5 && songRating > 3 {
    

    The print message disappears because one of the conditions is now false.

  3. Let’s try using the or operator. Copy the last if statement you added.

  4. Paste it at the bottom.

  5. Edit the line as shown, changing && to || by pressing the Shift–Backslash (\) key, located directly above the Return key on the keyboard.

    if numberOfVerses == 5 || songRating > 3 {
       print("Yes this is a good song")
    }
    

    This says if numberOfVerses is equal to 5 (which it is not) OR songRating is greater than 3 (which it is), then run. Only one of the conditions needs to be true in order to run.

  6. Now let’s do a string comparison. You compare strings the same way you compare numbers. At the bottom of Xcode, add the following code:

    songName = "Comfortably Numb"
    
    if songName == "Comfortably Numb" {
       print("Yep that is the song name")
    }
    

    This says to print the line if songName is equal to Comfortably Numb (which you set it to earlier).

  7. Let’s try combining logical operators. Add the following code in bold:

    if (numberOfVerses == 5 || songRating > 3) && songName == "Comfortably Numb" {
       print("Yes this is the right song")
    }
    

    Notice how we’ve had to enclose the or || condition between parentheses. This is because, just as in arithmetics the multiplication operator (*) takes precedence over the addition operator (+). In logic, the conjunction operator (&&) takes precedence over the disjunction operator (||). Thus, the same way we would need parentheses in the expression (A + B) * C in order to have A and B added before being multiplied by C, we need parentheses in the expression (A || B) && C, in order to have the disjunctive (or) expression evaluated before the conjunctive (and) expression.

  8. You should see the line printed: Yes this is the right song

Switch Statements

For more than three possible values, using an else/if statement is strongly discouraged. Instead, a switch statement can be used for more complex conditions, where there are multiple potential cases.

  1. In this next example, we want to evaluate whether a username matches a variable. Let’s go ahead and declare the variable first. Type the following at the bottom of Xcode:

    var userName = "DrFalken"
    
  2. The switch statement uses a certain format. The keyword switch is followed by the variable (in this case userName) whose value will determine which block of code to run. Type the following to set up the switch statement:

    switch userName {
    
    }
    
  3. Inside the curly braces we can add possible clauses, using the keyword case. We’ll add three cases we’d like to check for which if true, will each print an appropriate statement. Add the following in bold:

    switch userName {
    
       case "DrFalken", "David":
       print("Welcome, \(userName). Would you like to play a game?")
    
       case "Jennifer":
       print("Welcome, Jennifer!")
    
       case "McKittrick":
       print("I'm sorry, your access has been revoked.")
    
    }
    

    Notice that in the first case we’ve assigned two values to the same case, DrFalken and David, separated by commas.

  4. The default clause is used for any other possible values. To get rid of the red alert red circle error icon add the following bold code:

    switch userName {
    
       case "DrFalken", "David":
       print("Welcome, \(userName). Would you like to play a game?")
    
       case "Jennifer":
       print("Welcome, Jennifer!")
    
       case "McKittrick":
       print("I'm sorry, your access has been revoked.")
    
       default: 
       print("I'm sorry, \(userName), but you are not authorized to log in.")
    
    }
    

    NOTE: The default clause is required unless all possible cases have been explicitly listed. The only cases in which we can get away without a default clause is in the case of booleans and enumerations. Enumerations will be covered in future sections.

  5. Since the username we declared is DrFalken, you should see Welcome, DrFalken. Would you like to play a game? printed.

  6. Save and close the file. Keep Xcode open, as we’ll use it in the next exercise.

How to Learn iOS & Web Development

Master iOS development, web development, coding, and more with hands-on training. iOS development involves designing apps for Apple mobile devices with tools like Xcode and SwiftUI.

Yelp Facebook LinkedIn YouTube Twitter Instagram