2 - Introduction to Swift: Part 2

Welcome to the second part of the introduction to swift programming! In the first part we went over a bunch of different data types (Numbers, Strings, Booleans), different types of operators, and how to store datatypes in constants and variables! In this lesson we will go over control flow, or basically different ways we can process information in basic swift programs!

Conditionals

Conditionals are basically checkpoints that determine whether a certain value matches a condition specified by the developer, hence the name. If you remember our boolean operators from the last lesson, there are several different comparator operators that output true or false. We can use these operators in our conditionals. Let’s look at if statements first

If Statements

// We use the keyword if
if 2 > 1 {
    print("Yes, 2 is greater than 1.")
}

So what happened above:

  1. We use the keyword if to specify that we are making a conditional statement
  2. We follow if with our condition, in this case we are asking if 2 is greater than 1
  3. The code that occurs inside of the braces only occurs if the condition is met

And since the condition is obviously true (since 2 is greater than 1), then the print statement is executed! If we changed the conditional to 2 < 1 then the print statement would never be executed because the conditional is not true.

We can make more complex if statements using other keywords such as else and else if:

var animal:String = "Bear"

if animal == "Cat" {
    print("Meow!")
} else if animal == "Dog" {
    print("Woof!")
} else {
    print("Whatever sound a \(animal) makes!")
}

In this case we are using a string variable we created called animal with a few conditionals:

  1. If the animal is a cat (hense the == operator), then print Meow.
  2. If the first condition fails, then if the animal is a dog, print Woof.
  3. If the other conditionals fail, then print whatever sound the animal makes.

Since our animal is a bear, the proper output should be “Whatever sound a Bear makes!”

Here’s a more practical example using my account balance:

var myAccountBalance:Double = 200.00

var whatImGoingToWithdraw:Double = 50.00

if whatImGoingToWithdraw < myAccountBalance {
    myAccountBalance -= whatImGoingToWithdraw
    print("You have \(myAccountBalance) left in your bank account.)
} else if whatImGoingToWithdraw == myAccountBalance {
    print("WARNING: YOU'RE ABOUT TO BE IN A VERY BAD SITUATION")
} else{
    print("ERROR: JUST STOP TRYING DUDE!)
}

Explanation:

So I start with $200, and what I am trying to withdraw is $50. If the amount I’m trying to withdraw is less than my account balance, then the withdrawal is successful and it actually subtracts the withdrawal from my account balance variable. If the amount I’m trying to withdraw is equal to my account it prints a warning message, and if the amount is more than my account balance the program prints an error message.

Switch Statements

Here’s another conditional programming method. Switch statements are good for dealing with many different cases. It would be annoying to write if, else if, else if, else if… for a ton of different situations. Here is an example of how to use switch to simplify the different number of days in each month:

let birthMonth: Int = 11
var daysInMonth: Int

switch birthMonth {
case 1, 3, 5, 7, 8, 10, 12:
    daysInMonth = 31
case 4, 6, 9, 11
    daysInMonth = 30
case 2
    daysInMonth = 28
default:
    print("Invalid Birth Month")
}

In this situation we are passing in a constant called birthMonth into the switch statement. My birth month is 11, so it identifies whether the birthMonth falls under which of the following cases:

  1. Either month number 1, 3, 5, 7, 8, 10, and 12. If it is any of these numbers, then there are 31 days in that month, and so it sets the variable daysInMonth to 31.
  2. If the first case isn’t hit, then sees if it falls under the next case of 4, 6, 9, or 11… starting to see the path?

It will trickle down these cases until it hits one that is satisfies, or until it hits the default case that will execute if no other case occurs.

Let’s try a slightly more complex example:

let numba = 10

switch numba {
case _ where numba % 2 == 0:
    print("Even")
default:
    print("Odd")
}

In this example, we declare a constant numba to be 10. Then we say: “for every case in which numba % 2 == 0 (clever way to determine whether a number is even) then print “Even”, if not print “Odd””.

Ternary Conditional Operator

This is a way to shorted if-else statements to simplistinc one liners if possible. They are formatted with a conditional equation followed by a ?:

var withdraw: Int = 50
var balance: Int = 200

// Format: condition ? (value if condition is true) : (value if condition is false)

balance = withdraw < balance ? balance - withdraw : balance

Ok what just happened?

  1. We have two variables, one for what I want to withdraw and one for my current balance
  2. I want to change my balance to account for what I withdraw if the withdrawal amount is less than my current balance
  3. So if withdraw < balance then balance = balance - withdraw, if not then balance = balance.

This may be a little confusing, and there might not be many situations in which you will use ternary operators, but they are nifty if we are writing consise code. Try some examples on your own to see how they work.

Loops

As they implicitly describe, loops are ways to repeat sections of code. We can repeat code a certain number of times, until a certain condition is met, or infinitely if we want (not recommended).

While Loops

We can use the keyword while to perform a while loop:

var sum = 1
while sum < 1000 {
    sum += 1
}

In this scenario, we create a variable called sum that starts out with a value of 1, and the while loop states that the code inside of the braces will execute over and over until sum is less than 1000. If we didn’t change the value of sum inside of the braces to get closer to 1000 over time, then the loop would go on forever. 1 is being added to sum each time, and so the loop will execute 999 times until sum is equal to 1000. When that happens, the while condition is broken and the loop stops.

We can perform a similar loop with the keyword repeat and while:

sum = 1
repeat {
    sum += 1
} while sum < 1000

In this scenario we are doing the same thing, we are repeating the code inside of the braces and then the condition is checked at the end of the loop instead of at the beginning. The only difference in between this situation and the first one is that the code inside of the braces will occur at least once even if the condition checked at the end doesn’t match.

One final way we can do the exact same thing:

sum = 0
while true {
    sum += 1
    if sum >= 1000 {
        break
    }
}

In this scenario we are looping while true, which actually means “loop forever” since true is always true. The only way to break out of the infinite loop is to “break” it. We have nested an if conditional statement within the loop that checks to see if sum is ever greater than or equal to 1000, and when this condition is fulfilled, calls the keyword break which ends the loop!

For Loops

This is another very common loop. If you are familiar with loops in other languages, they tend to look slightly different than swift for-loops:

sum = 0
for i in 1...1000 {
    sum += 1
}

This loop is slightly different than a while loop. In this example, we declare that for every value from 1 to 1000 we are going to execute whatever we put in the braces (in this case we are incrementing sum by 1). This will loop 1000 times, with the variable (created after the for keyword) i going from 1, 2, 3, 4… 999, 1000. Done. Here’s a slightly different example:

sum = 0
for i in 1..<1000 {
    sum += 1
} 

The main difference here is in the incrementation from 1 to 1000. Instead of three periods meaning from 1 to 1000 including 1000, 1..<1000 means from 1 until 1000, which doesn’t include 1000. This above example will only loop 999 times.

Let’s make this more complex by adding another conditional to the for-loop:

for i in 1...1000 where i % 2 == 1 {
    sum += 1
}

The above loop incorperates the where keyword which adds another condition in order for the loop to run. This loop will run 500 times since it only runs when i % 2 == 1 which occurs when i is an odd number.

Enumerations

An enumeration is a way to describe a variable that can have different values, for example if we wanted to create an enumeration of things that a bear does (this is not the best example, but bear with me ;):

enum BearThings: String {
    case angry = "RAWR"
    case hungry = "YUM YUM"
    case sleepy = "HMMMMBRJRM"
}

BearThings.angry.rawValue // will be "RAWR"

This way we can access different things about a bear through the BearThings enumeration instead of declaring three different string variables.

Ok so that’s it for this lesson, we have one more introduction to swift lesson before getting into the real iOS programming stuff. Stay tuned.

Tags:

Updated: