Swift Basics Part 4

Swift Basics Part 4

For those of you who have been following along since my first post, I'm sure you're starting to wonder, "is he ever going to write about actually making an app?" I promise, it's coming soon. I want you to have a good grasp of the basics so you aren't completely lost once things get a little more complicated. With that in mind, for this post I am going to discuss Conditionals and If Statements. This is where we'll start to see the logic of programming and how the computer can make decisions for us, based on various sets of instructions. Let's get started.

Conditionals and If Statements

When I talk about conditionals I am talking about writing conditions that, when satisfied, will execute different sets of logic. You likely already know about conditional logic and have applied it in your own life:

  • if the elevator is broken, take the stairs
  • if you feel hungry, eat food
  • if you are cold, put on a jacket.

The list can go on and on. You can see from these examples that we make numerous decisions on whether to do one thing or another. That same logic can be applied in a programming language using if statements.

If you've been following along with my other posts, you likely already have a playground file open with the Person struct already created. If you don't, add the code below to a playground file so you can follow along.

struct Person {
    let name: String
    let birthMonth: String
    var age: Int

    func greetPerson(name: String) {
        print("Hello there, \(name)!")
    }
}

If Statements

So, what is an If Statement and how do we represent it in code? Well, it really is quite simple and follows the simple structure of "if this is true, do this." I'll use an example to demonstrate how we do this in code. Let's check and see if a person instance we create has the name "John." If the name is "John," we'll print True. Add the following lines of code to your playground file:

let person = Person(name: "John", birthMonth: "February", age: 38)

if person.name == "John" {
    print("True")
}

Run the playground file and see what happens. Since our person's name is "John," we will enter the body of the if statement and run any code within the {}. In this example, we only have one line of code within the curly brackets, print("True"). You should see that True is printed in the Debug window.

Comparison Operators

Now you might be wondering, what is with the ==? That double equals sign represents one of the Comparison Operators that are made available to us in Swift. Comparison operators, as their name suggests, allow us to make comparisons between two elements. In our case, we were comparing the value of person.name with the value of "John". The == is checking to see if the two values are exactly the same. Since the value of person.name and the value of "John" are the same, we saw that "True" was printed in the Debug window. There are multiple operators in Swift that we use to make comparisons:

  • Equal to: a == b
  • Not equal to: a != b
  • Greater than: a > b
  • Less than: a < b
  • Greater than or equal to: a >= b
  • Less than or equal to: a <= b

If-Else Statements

Right now, our current if statement does not have much functionality. If the name is "John" we'll print "True," but if it isn't we aren't doing anything. Go ahead and change the name of your person instance to anything else and rerun the playground. Notice, nothing gets printed to the Debug window. How can we add more functionality to see when our condition isn't met? That is where the else comes in handy. Modify your if statement to the following:

if person.name == "John" {
    print("John")
} else {
    print("Not John")
}

Now, if the person's name is "John" we'll print "John," otherwise we'll use the code within the else block and print "Not John." Go ahead and run your playground to confirm you can get "John" to print if your person's name is "John" and print "Not John" when you change it to any other name. This is great! We are now starting to expand the logic of our if statement. To expand the logic even further, we are going to add an else-if clause.

Else-If Statements

Adding an else-if statement allows us to further expand the conditions that our if statement can evaluate against. It is quite simple to add an else-if to our existing if statement. Modify your existing if-else statement to match the following:

if person.name == "John" {
    print("John")
} else if person.name == "Bob" {
    print("Bob")
} else {
    print("Not John or Bob")
}

As you can see, all we had to do was drop in another if statement after the first else to add an additional condition. Now, if our person's name is "John" or "Bob," we'll see a name get printed to the Debug window. Please note, that this is the structure you have to follow, if, else if, else. If you try adding an else if clause after your else clause you will receive an error in Xcode.

We could keep adding additional else-if clauses for every name we can think of, but I think you get the picture. Let's turn our attention now to the final thing I want to talk about in this post, the Logical Operators.

Logical Operators

In Swift, we have three logical operators that we can work with - AND, OR, and NOT. What are these logical operators? AND and OR are the operators that let us combine two expressions and evaluate the outcome. NOT allows us to negate the value of an expression. Let's look at examples of how you can implement each of these in Swift, starting with the OR operator:

if person.name == "John" || person.name == "Bob" {
    print("Person has a name")
} else {
    print("No name given")
}

In this first example, we are using the OR operator, represented in code by the dual pipes ||. The OR operator only requires one of our conditions to be true in order for the entire expression to evaluate to true. So in this case, our person instance has the name of "Bob," so we will print "Person has a name" to the debug window.

Let's look at a second example:

let number1 = 88
let number2 = 44

if (number1 > number2) && (number2 / 2 != 0) {
    print("True")
}

There is a little bit more going on here, but it's simple enough to understand once you break it down.

  1. First, we declare two constants number1 and number2.
  2. Next, we create our if statement and our first condition, which is number1 > number2. Since number1 = 88 and number2 = 44, this first condition will evaluate to True.
  3. Next, we can look at the second expression, number2 / 2 != 0, and see that 44 divided by 2 is 22, which does not equal 0. So this second condition will evaluate to True as well.
  4. Finally, we combine the two expressions with the AND operator, represented in Swift by the double ampersand &&. If we evaluate two True expressions with the AND operator we get a True result. Therefore, we should see "True" printed in the Debug window. Run your playground file to verify you see "True" printed in the Debug window.

Finally, let's take a look at using the NOT operator:

print(!true)

The NOT operator is represented in Swift by an exclamation point, !, placed in front of what you are negating (this is important as the ! has another use in Swift, but more on that in a future post). If you run this line of code in your playground, you should see that you get "false" printed in the debug window. This is what the NOT operator does, it makes a true statement false and a false statement true. Useful for when you want to toggle values back-and-forth, but more on that in a future post :).

Wrap Up

As I'm sure you can imagine, there are endless possibilities for how you can combine conditional and logical operators to get some truly complex logic. I encourage you to play around with different conditions and operators and see what kinds of things you can come up with. I'll even leave you with a challenge for some additional practice. Without running the following in a playground, what do you expect to be printed in the Debug window? Think about it, then run it to see if you were correct. Once you've done that, change each of the variables as you need to in order to get every print statement to print in the Debug window at least once.

var age = 23
var money = 20000
var debt = 5001
var creditScore = 600

if age >= 18 && money >= 20000 {
    if debt <= 5000 {
        if creditScore >= 700 {
            print("I can get a car for $\(money - debt)")
        } else {
            print("I have the money, but my credit isn't good enough")
        }
    } else {
        print("I have money, but I should probably use it to pay off my debt")
    }
} else {
    print("I can't get a car just yet")
}

In the next post, we'll start digging in to some actual app development, so get excited for that! In the meantime, happy coding!