Introduction to Swift

Apr 24 2024 · Swift 5.10, iOS 17, Xcode 15

Lesson 02: Flow Control & Functions

if & switch Demo

Episode complete

Play next episode

Next
Transcript

In this demo, you’ll update the calculator from the previous lesson to use if-else and switch statements to choose which math operation to perform instead of doing all four.

Open Xcode on your Mac and create a new playground.

Start by creating the two constants you’ll use as input with the type Int.

let int1 = 10
let int2 = 5

Then, create a string to hold the operator you’ll refer to for the math operation. Give it the string value of "+" to start:

let intOperation = "+"

Next, create two variables to store the result and the user-friendly text message that describes the operation. The values for these are going to change, so declare them with var rather than let:

var result = 0
var resultMessage = ""

Now, for the fun part. You want to decide which operation to perform based on the value of intOperation. If it’s the plus sign (+), then it’s an addition, the minus sign (-) is subtraction, the asterisk (*) is multiplication and the forward slash (division sign /) is division. Write that using Swift if and else statements:

if intOperation == "+" {

} else if intOperation == "-" {

} else if intOperation == "*" {

} else if intOperation == "/" {

}

You have the logic to decide what to do in place. What’s left is to write the code for each decision. In the addition decision block where intOperation equals "+", set the value of result to the sum of the two numbers, and set resultMessage to the text message you want to give the user:

result = int1 + int2
resultMessage = "Integer sum of \(int1) and \(int2) is: \(result)"

Now, below all of the if and else statements, print the two values result and resultMessage:

print("Result: \(result)")
print("Message: \(resultMessage)")

Run the playground to see the output from your code so far. Although you didn’t add the code for the other three operations, it doesn’t matter yet because the value of intOperation will go through the addition logic you’ve added. If you change its value to "-", result is zero and resultMessage is an empty string.

Change the value of intOperation to "-" and run the playground to try it out.

Now, you can complete the other code blocks for the other operations. Add this for the subtraction block:

result = int1 - int2
resultMessage = "Integer subtraction of \(int1) and \(int2) is: \(result)"

Add this for the multiplication block:

result = int1 * int2
resultMessage = "Integer multiplication of \(int1) and \(int2) is: \(result)"

And, finally, add this for the division block:

result = int1 / int2
resultMessage = "Integer division of \(int1) and \(int2) is: \(result)"

Change the value of intOperation to any of the four values — "+", "-", "*" or "/" — and run the playground to try your code. Look at the bottom pane to see the printed messages.

If you accidentally change the value to anything other than the four expected values, none of the four if statements executes and nothing happens. You end up with empty result.

For example, you set the value of intOperation to "x" instead of "*". Your code won’t do any of the calculations, and it might take you a minute to understand what’s going on and that the input was wrong. A way to save yourself those few minutes is to have an else at the end of the four conditions to set the message to tell you that the app didn’t know which operation to perform. Add this right after the closing braces of the division code block:

else {
  resultMessage = "Unknown Operator"
}

Set the value of intOperation to anything other than the four expected values and run the Playground. The message now shows that the code didn’t know which decision to make. You can make the message even more helpful by adding some information:

else {
  resultMessage = "\(intOperation) is an unknown operator."
}

When your app has a lot of if conditions in many places and many decisions to take, those messages can make an enormous difference in helping you understand what’s happening in your code. You’ll also get ideas about which additional conditions you might need to include so your app doesn’t give unexpected results.

Now that you tried out if and else, how about using swich instead?

Add this at the end of your playground. You don’t need to remove any of the previous code:

switch (intOperation) {
case "+":

case "-":

case "*":

case "/":

default:

}

Once you enter the code like this, Xcode will complain on each case and the default lines, saying they must have at least one executable statement. Don’t worry about that because you’ll add them now.

Just like the if conditions from before, add the result and resultMessage lines where they belong:

result = int1 + int2
resultMessage = "Integer sum of \(int1) and \(int2) is: \(result)"
...
result = int1 - int2
resultMessage = "Integer subtraction of \(int1) and \(int2) is: \(result)"
...
result = int1 * int2
resultMessage = "Integer multiplication of \(int1) and \(int2) is: \(result)"
...
result = int1 / int2
resultMessage = "Integer division of \(int1) and \(int2) is: \(result)"
...
resultMessage = "Unknown Operator"

Then, add the two print statements to see the results:

print("Result: \(result)")
print("Message: \(resultMessage)")

Run the playground. You can see that the messages from the if condition results match the ones from the switch statement.

Both ways of logic for branching, the name for this type of flow control, are valid. One could be better than the other depending on the situation. It’s up to you to judge when to use either and do your best to make your code look organized and easy to understand.

See forum comments
Cinema mode Download course materials from Github
Previous: Flow Control Next: Using Loops