Programming in Swift: Fundamentals

Oct 19 2021 · Swift 5.5, iOS 15, Xcode 13

Part 1: Core Concepts

05. Logical Operators

Episode complete

Play next episode

Next
About this episode

Leave a rating/review

See forum comments
Cinema mode Mark complete Download course materials
Previous episode: 04. Challenge: Booleans Next episode: 06. Challenge: Logical Operators

Get immediate access to this and 4,000+ other videos and books.

Take your career further with a Kodeco Personal Plan. With unlimited access to over 40+ books and 4,000+ professional videos in a single subscription, it's simply the best investment you can make in your development career.

Learn more Already a subscriber? Sign in.

Notes: 05. Logical Operators

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

Heads up... You've reached locked video content where the transcript will be shown as obfuscated text.

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. In this video, you'll learn about another set of operators that are designed for working with Boolean values and expressions. These are known as logical operators. Now, logical operators let you do things like check if at least one Boolean value in a whole set is true, if all Boolean values in a set are true, or even to check if a Boolean value is not true. Does that sound strange? Okay, but that's okay. You'll learn how these work as you work through the demo. Open up a playground for this video, and you'll see that I've set up some predefined constants for you. Now, following on the examples from the previous video, I've put some constant values in here that deal with the grades of some students. So here I've defined some Booleans using type inference that check whether or not our illustrious students have passed. You'll use these values as you work through some exercises about logical operators. So the first logical operator is simple, that's the NOT operator. That's represented in Swift as a single exclamation mark placed before a constant or variable name. If I wanna check the opposite or inverse of whether Sam passed, I simply write NOT samPassed. And this tells me that this is false, because Sam did in fact pass. And I can also check to see if Chris did not pass by doing the same thing here, NOT chrisPassed. And in this case it's true, because it's true that Chris did not pass. Now, it may seem kind of strange to check the inverse of a Boolean, but when you start writing more complicated logic later on, you're often gonna want to run a particular block of code only when a particular value or a set of values is not true. So to avoid writing weird code like this, you can simply use the NOT operator to make the meaning more clear. Now, this NOT operator only applies to Booleans. So what do you think happens if you try to use the NOT operator on something like a string value? Well, let me set up a constant, catName, and I'll set it to Ozma. Now if I try to say NOT 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. Now let's comment that out since that code doesn't make any sense. The next logical operator is the AND operator. It's pretty similar to the way you think about the word and in English. Is this true and is that true? Do you want ice cream and sprinkles? You represent AND in Swift with two ampersand symbols. That's right, it's the and sign. You 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. 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 both true. And 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? Well, that brings you to the next logical operator, OR. Again, the OR operator is somewhat analogous to the word or in English. Are we having cake or pie for dessert? Now, the one small difference is that in English we usually mean or as exclusive in that you want either pie or cake, but the OR operator simply means if any one of these things is true, then this whole expression is true. Now the next operator is the OR operator. The OR operator is two vertical lines or pipes. You can usually find this character in the very top row of a keyboard. So again, let me define a constant, I'll call it eitherPassed, and I'll set that to either chrisPassed OR samPassed. And in this case, you see that at least one of these two passed, so the result is true. Now 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, the result would be false. Now you aren't limited just using two values for OR or AND operators. You can string together as many as you like. For instance, I have this anonymous student up here. They have a grade and they also have a passed value. So what I want to know is if any one of all the three students passed. So let me create a constant, anyonePassed, and I'll set it to chrisPassed OR samPassed OR studentPassed, like this. So here we know at least one person passed, so this entire expression is true. So what if we wanted to know if everyone passed, that is, are all of the values in this statement true? You can do that with multiple AND operators, just like you did with multiple OR operators. So I'll declare a constant, everyonePassed, and I'll set it to chrisPassed AND samPassed AND studentPassed. And you see that no, not everyone passed because just one of these values is false, chrisPassed, the entire expression becomes false. Now, 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 or OR operators. So 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. So let me capture that in two constants. One, the merit award grade of 90. And let's capture Sam's perfect attendance in a constant, samHasPerfectAttendance, and set that to true. It must be nice to be perfect, Sam. Anyway. So, we need to build up an expression that determines, A, if Sam has perfect attendance, and B, if Sam also has a mark over 90. So 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. And we see that, yes, Sam has perfect attendance and his mark is over 90. Swift first calculates the value of samGrade greater than meritAwardGrade to be true. And then it goes on to evaluate the other Boolean values in the expression. Now, since both are true, then the entire expression is true as well. Congratulations, Sam! Now, what about Chris? Well, let's set up a similar test for Chris. Now, Chris also has perfect attendance. And then we create another constant, chrisIsMeritStudent, and we set that to chrisHasPerfectAttendance AND chrisGrade is greater than meritGrade. And we see, to no one's great 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. And I wanna 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 message if Chris is a merit student like so. 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 or something in the case where he isn't a merit student. So you can tack on what's known as an else clause to this if statement to turn it into an if else statement. So, the playground executes and you can see that "Keeps studying" is printed out to the console. Swift checks the value of chrisIsMeritStudent, sees that it's false. It knows to ignore what's in the if clause and only execute what's in the else clause of the whole block. You can easily operate on expressions too. Now, let me define a variable to hold the name of the better student. No, 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 will take the value of Sam. But if that's not true, then betterStudent will take the value of the string Chris. And in this case, you can see that clearly Sam is the better student. Swift evaluated whether samGrade is greater than chrisGrade. It found that to be true and then executed the code in the if block and ignored the code in the else block. Now there's one last thing I wanna show you, and that's what's known as the ternary conditional operator. Now the ternary conditional operator is a lot like an if-else statement, which is why I'm showing it to you right here. 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. And 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 statement above to say betterStudent gets the value, depending on whether samGrade is greater than chrisGrade. If true, return Sam, but if not true, return Chris. So the ternary conditional operator looks a bit strange. You first have an expression, which can evaluate to either true or false. You then put a question mark followed by the value to return if the expression is true, and then a colon, and then you put the value to return if the expression is false. 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 series of challenges that will walk you through a few more conditional operator exercises.