Programming in Swift: Fundamentals

Oct 19 2021 Swift 5.5, iOS 15, Xcode 13

Part 1: Core Concepts

5. Logical Operators

Lesson Complete

Play Next Lesson
Next
Save for later
About this episode
See versions

See forum comments
Cinema mode Mark as Complete Download course materials
Previous episode: 4. Challenge: Booleans Next episode: 6. Challenge: Logical Operators

Update Notes: The student materials have been reviewed and are updated as of October 2021.

In the previous set of exercises, you saw how you can work with Boolean values, and how you could use comparison operators such as less than, greater than, equal to and not equal to to compare values to each other.

Logical operators let you do things like check if at least one Boolean value in a set is true, if all Boolean values in a set are true, or even to check if a Boolean value is not true. Sound strange? That’s OK - you’ll learn how these work as you work through the demo.

Open up the playground for this video, and you’ll see that I’ve set up some predefined constants for you:

let passingGrade = 50
let studentGrade = 50
let chrisGrade = 49
let samGrade = 99

Following on the examples from the previous video, I’ve put some constant values in here that deal with some grades of some students.

let studentPassed = studentGrade >= passingGrade
let chrisPassed = chrisGrade >= passingGrade
let samPassed = samGrade >= passingGrade

Here, I’ve defined some Booleans (through type inference) that check whether or not our illustrious students passed. You’ll use these values as you work through some exercises about logical operators.

The first logical operator is simple: the not operator. It’s represented in Swift as a single exclamation mark, placed before the constant or variable name. If I want to check the opposite, or inverse, of whether Sam passed, I simply write “not samPassed”:

!samPassed

And this tells me that this is false, because Sam did pass. And I can also check to see if Chris did not pass, by doing the same thing here: “not chrisPassed”:

!chrisPassed

And in this case, it’s true, because it’s true that Chris didn’t pass.

It may seem strange to check the inverse of a Boolean, but when you start writing more complicated logic later on, you’ll often want to run a particular block of code only when a particular value or set of values isn’t true. So to avoid writing weird code like this:

chrisPassed == false

You can simply use the not operator to make the meaning more clear.

Now, this not operator only applies to Booleans. What do you think happens if you try to use it on something like a String value?

Let me set up a constant catName and set it to “Ozma”:

let catName = "Ozma"

If I try to say “not catName”,

!catName

Swift really has no idea what the inverse of Ozma is, so it throws an error: Logical operations are really only useful for Booleans.

Let’s comment that out, since that code doesn’t make sense.

//!catName

The next logical operator is the AND operator. It’s pretty similar to they way you’d think about the word “AND” in English; is this true, AND is that true? Do you want ice cream AND sprinkles?

// AND Operator
// &&

You represent AND in Swift with two ampersand symbols - that’s right, the AND sign!

We can use the AND operator to see if both Chris and Sam passed.

Let me define a constant bothPassed, and I want this to be true if both chrisPassed and samPassed are true:

let bothPassed = chrisPassed && samPassed

And you can see that no, both Sam and Chris didn’t pass. This expression will only be true if both values on either side of the AND operator are true. In this case, we know that chrisPassed is false, so this entire expression can’t be true.

Now, what if you just want to know if one or the other has passed? That is, you don’t care who passed, just that one of Sam or Chris passed?

The OR operator is two vertical lines, or pipes; you can usually find this character in the very top row of your keyboard.

// OR Operator
// ||

Again, I define a constant eitherPassed, and set that to chrisPassed OR samPassed:

let eitherPassed = chrisPassed || samPassed

And in this case, you see that at least one of those two passed, so the result is true. Even if both of these students had passed, the result would still be true. And if not a single person in that group had passed, then the result would be false.

You aren’t limited to just two values for OR and AND operators; you can string as many together as you like. For instance, I have this anonymous student who has a grade and a passed value. What if I want to know is, if any one of these three people passed?

Let me create a constant, anyonePassed, and I’ll set it to chrisPassed OR samPassed OR studentPassed, like so:

let anyonePassed = chrisPassed || samPassed || studentPassed

Here, we know at least one person passed, so this entire expression is true.

What if you wanted to know if everyone passed; that is, are all of the values in a statement true?

You can do that with multiple AND operators, just like you did with multiple OR operators.

I’ll declare a constant, everyonePassed, and I’ll set it to chrisPassed AND samPassed AND studentPassed:

let everyonePassed = chrisPassed && samPassed && studentPassed

And you see that no, not everyone passed. Because just one of these values is false, chrisPassed, the entire expression becomes false.

What’s nice about building up these Boolean expressions this way is that you can mix and match them with the comparison operators you learned about in the previous video. So you can use things like greater than or less than operators along with these new AND and OR operators.

To see this in action, let’s assume that any student who has perfect attendance AND has a mark over 90, gets a special merit award.

Let me capture that in two constants: one, the meritAwardGrade of 90:

let meritAwardGrade = 90

…and let’s capture Sam’s perfect attendance in a constant, samHasPerfectAttendance:

let samHasPerfectAttendance = true

Must be nice to be perfect, Sam!

So, we need to build up an expression that determines (a) if Sam has perfect attendance, and (b) if Sam has a mark over 90.

Let me create another constant to hold the result of this: samIsMeritStudent, and I’ll set that to samHasPerfectAttendance AND samGrade is greater than meritAwardGrade:

let samIsMeritStudent = samHasPerfectAttendance && samGrade > meritAwardGrade

And we see that yes, Sam has perfect attendance AND his mark is over 90. Swift first calculates the value of samGrade greater than merit AwardGrade to be true, and then it goes on to evaluate the other Boolean values in the expression. Since both are true, then the entire expression is true as well. Congratulations, Sam!

Now, what about Chris? Let’s setup a similar test for Chris.

Now, Chris also has perfect attendance:

let chrisHasPerfectAttendance = true

And then we create another constant chrisIsMeritStudent, and set that to chrisHasPerfectAttendance AND chrisGrade > meritGrade:

let chrisIsMeritStudent = chrisHasPerfectAttendance && chrisGrade > meritAwardGrade

And we see, to no one’s surprise, that Chris’ grade is not greater than the merit award grade, so it doesn’t matter that he has perfect attendance: the value of this entire expression becomes false.

Now, you worked with some simple if statements back in the first portion of this course, building up your first iOS app. I want to show you a nice extension to if statements, which is an if-else statement, which lets you perform an action if the expression in the if statement turns out to be false.

I can create a simple if statement to print out a congratulatory String, if Chris is a merit student, like so:

if chrisIsMeritStudent {
    print("Congratulations!")
}

Well, nothing prints out here, because we know that Chris is not a merit student. Poor Chris. But we should have something to say to him, maybe some words of encouragement, in the case where he is not a merit student. You can tack on what’s known as an else clause to this if statment, to turn it into an if-else statement:

else {
    print("Keep studying.")
}

So the playground executes, and you can see that “keep studying” is printed out to the console. Swift checks the value of chrisIsMeritStudent, sees that’s it’s false, and it knows to ignore what’s in the if clause, and only execute what’s in the else clause of this whole block.

You can easily operate on expressions too; let me define a variable to hold the name of the better student:

var betterStudent: String

I don’t know who the better student is yet, so I haven’t assigned a value here. I’ll let my if-else statement do that for me.

So, let me compare Sam and Chris. If samGrade is greater than chrisGrade, then betterStudent takes the value of the string “Sam”. Else, if that is NOT true, then betterStudent takes the value of the string “Chris”:

if samGrade > chrisGrade {
    betterStudent = "Sam"
} else {
    betterStudent = "Chris"
}

And in this case, you can see that clearly, Sam is the better student. Swift evaluated whether samGrade is greater than chrisGrade, found that to be true, and then executed the code in the if block, and ignored the code in the else block.

There’s one last thing I want to show you, and that’s what’s known as the ternary conditional operator. It’s a lot like an if-else statement, which is why I’m showing it to you here.

// Ternary conditional operator

You can see that this is a bit like an if-else statement, where there are two choices to return depending on what the expression evaluates to.

Since all my if-else statement above does is to assign a String to a variable depending on the result of the expression, I can easily rewrite the if statement above to say betterStudent get the value, depending on whether samGrade is greater than chrisGrade, and true, return “Sam”, but if not true, return “Chris”:

The ternary conditional operator looks a bit strange; you first have an expression, which can evaluate to either true or false; then you put a question mark followed by the value to return if the expression is true; then you put the value to return if the expression is false.

betterStudent = samGrade > chrisGrade ? "Sam" : "Chris"

And, as expected, Sam is the result of this whole thing. You can see that, in simple cases, it’s easy to use a ternary operator, instead of coding up an entire if-else statement.

So now that you’ve learned about logical conditional operators, it’s time to test your newfound knowledge with a set of challenges that will walk you through a few more conditional operator exercises!