Home > Articles > Programming > General Programming/Other Languages

  • Print
  • + Share This
This chapter is from the book

From Objective-C to Swift

If you are coming from the world of Objective-C and C, you know that you have many number types at your disposal. Number types like CGFloat and CFloat are necessary to construct certain objects. For example, SpriteKit has the SKSpriteNode as a position property, which uses a CGPoint with two CGFloats.

What is the different between CGFloat and Float? In this specific case we found that CGFloat is just a typealias for Double. This is what the code actually says:

typealias CGFloat = Double

What is a typealias? Great question. A typealias is just a shortcut to get to an already existing type by giving it a substitute name. You could give String an alternative name type of Text, like this:

typealias Text = String
var hello:Text = "Hi there"

Now hello is of type Text, which never existed before this point. So if CGFloat is a typealias for a Double, this just means that when you make CGFloats, you are really just making Doubles. It’s worth it to Command+click around and see what is mapping to what. For example, a CFloat is a typealias for Float, and a CDouble is a typealias for Double.

That does not mean that you can suddenly add them together. You still need to convert them to combine them. For example, this will not work:

var d = 3.141
var g = CGFloat(3.141)
print(d + g)

To fix this example we would need to do something like this:

var d = 3.141
var g = CGFloat(3.141)
print(CGFloat(d) + g)

Control Flow: Making Choices

Controlling the order in which your code executes is obviously a crucial aspect of any programming language. By building on the traditions of C and C-like languages, Swift’s control flow constructs allow for powerful functionality while still maintaining a familiar syntax.

for Loops

At its most basic, a for loop allows you to execute code over and over again. This is also called “looping.” How many times the code gets executed is up to you (maybe infinitely). In the Swift language, there are two distinct types of for loops to consider. There is the traditional for-condition-increment loop, and there is the for-in loop. for-in is often associated with a process known as fast enumeration—a simplified syntax that makes it easier to run specific code for every item. for-in loops give you far less code to write and maintain than your typical C for loops.

for-condition-increment Loops

You use a for-condition-increment loop to run code repeatedly until a condition is met. On each loop, you typically increment a counter until the counter reaches the desired value. You can also decrement the counter until it drops to a certain value, but that is less common. The basic syntax of this type of loop in Swift looks something like this:

for initialization; conditional expression; increment {
    statement
}

As in Objective-C and C, in Swift you use semicolons to separate the different components of the for loop. However, Swift doesn’t group these components into parentheses. Aside from this slight syntactic difference, for loops in Swift function as they would in any C language.

Here’s a simple example of a for-condition-increment loop that simply prints Hello a few times:

for var i = 0; i < 5; ++i {
    print("Hello there number \(i)")
}
// Hello there number 0
// Hello there number 1
// Hello there number 2
// Hello there number 3
// Hello there number 4

This is fairly straightforward, but notice the following:

  • Variables or constants declared in the initialization expression only exist within the scope of the loop. If you need to access these values outside the scope of the for loop, then the variable must be declared prior to entering the loop, like this:

    var i = 0
    for i; i < 5; ++i {...
  • If you’re coming from another language, particularly Objective-C, you will notice that the last example uses ++i instead of i++. Using ++i increments i before returning its value, whereas using i++ increments i after returning its value. Although this won’t make much of a difference in the earlier example, Apple specifically suggests that you use the ++i implementation unless the behavior of i++ is explicitly necessary.

for-in Loops and Ranges

In addition to giving you the traditional for-condition-increment loop, Swift builds on the enumeration concepts of Objective-C and provides an extremely powerful for-in statement. You will most likely want to use for-in for most of your looping needs because the syntax is the most concise and also makes for less code to maintain.

With for-in, you can iterate numbers in a range. For example, you could use a for-in loop to calculate values over time. Here you can loop through 1 to 4 with less typing:

class Tire{}
var tires = [Tire]()
for i in 1...4 {
    tires.append(Tire())
}
print("We have \(tires.count) tires")

We haven’t covered the class and array syntax yet, but maybe you can take a guess at what they do. This example uses a ... range operator for a closed range. The range begins at the first number and includes all the numbers up to and including the second number.

Swift also provides you with the half-open range operator, which is written like this:

1..<4

This range operator includes all numbers from the first number up to but not including the last number. The previous example, rewritten to use the non-inclusive range operator, would look like this:

class Tire{}
var tires = [Tire]()
for i in 1..<5 {
    tires.append(Tire())
}
print("We have \(tires.count) tires")

As you can see, the results are almost identical and both examples provide concise and readable code. When you don’t need access to i, you can disregard the variable altogether by replacing it with an underscore (_). The code now might look something like this:

class Tire { }
var tires = [Tire]()
// 1,2,3, and including 4

class Tire {}
var tires = [Tire]()
for _ in 1...4 {
    tires.append(Tire())
}
print("We have \(tires.count) tires")

Let’s pretend that a bunch of tires have gone flat, and you need to refill each tire with air. We could use the for in loop to loop through all of our tires in the tire array. We can add on to our earlier example by giving the tires air. You could do something like this:

class Tire { var air = 0 }
var tires = [Tire]()
for _ in 1...4 {
    tires.append(Tire())
}
print("We have \(tires.count) tires")

for tire in tires {
    tire.air = 100
    print("This tire is filled \(tire.air)%")
}
print("All tires have been filled to 100%")

With this type of declaration, Swift uses type inference to assume that each object in an array of type [Tire] will be a Tire. This means it is unnecessary to declare the type Tire explicitly. In a situation in which the array’s type is unknown, the implementation would look like this:

class Tire { var air = 0 }
var tires = [Tire]()
for _ in 1...4 {
    tires.append(Tire())
}
print("We have \(tires.count) tires")

for tire: Tire in tires {
    tire.air = 100
    print("This tire has been filled to \(tire.air)%")
}

In this example we told the loop that each tire in the array of tires is going to be specifically of type Tire. In this specific example there is not a good reason to do this, but you may come upon a situation in which the type is not set explicitly. Since Swift must know what types it is dealing with, you should make sure that you communicate that information to Swift.

Looping Through Other Types

In Swift, a String is really a collection of Character values in a specific order. You can iterate values in a String by using a for-in statement, like so:

for char in "abcdefghijklmnopqrstuvwxyz".characters {
    print(char)
}
// a
// b
// c
// etc....

As long as something conforms to the SequenceType, you can loop through it. You cannot loop through the string directly; you need to access its character property.

When looping, there will be situations in which you will need access to the index as well as the object. One option is to iterate through a range of indexes and then get the object at the index. You would write that like this:

let numbers  = ["zero", "one", "two", "three", "four"]
for idx in 0..<numbers.count {
    let numberString = array[idx]
    print("Number at index \(idx) is \(numberString)")
}
// Number at index 0 is zero
// Number at index 1 is one
// etc....

This works just fine, but Swift provides a much swifter way to do this. Swift gives you an enumerate method as part of the array, which makes this type of statement much more concise. Let’s use the for-in statement in with the enumerate method:

let numbers = ["zero", "one", "two", "three", "four"]
for (i, numberString) in numbers.enumerate() {
    print("Number at index \(i) is \(numberString)")
}
// Number at index 0 is zero
// Number at index 1 is one
// etc....

This is much clearer, and you would use it when you require an array element and its accompanying index. You can grab the index of the loop and the item being iterated over!

Up to this point, all the loops we’ve covered know beforehand how many times they will iterate. For situations in which the number of required iterations is unknown, you’ll want to use a while loop or a do while loop. The syntax to use these while loops is very similar to that in other languages. Here’s an example:

var i = 0
while i < 10 {
    i++
}

This says that this loop should increment the value of i while it is less than 10. In this situation, i starts out at 0, and on each run of the loop, i gets incremented by 1. Watch out, though, because you can create an infinite loop this way. There will be times when you really need an infinite loop.

One way to create an infinite while loop is to use while true:

while true {
}

In this example you use a while loop that always evaluates to true, and this loop will run forever, or until you end the program or it crashes itself.

This next example uses some of the looping capabilities plus if/else statements to find the prime numbers. Here’s how you could find the 200th prime number:

var primeList = [2.0]
var num = 3.0
var isPrime = 1
while primeList.count < 200 {
    var sqrtNum = sqrt(num)
    // test by dividing only with prime numbers
    for primeNumber in primeList {
        // skip testing with prime numbers greater
        // than square root of number
        if num % primeNumber == 0 {
            isPrime = 0
            break
        }
        if primeNumber > sqrtNum {
            break
        }
    }
    if isPrime == 1 {
        primeList.append(num)
    } else {
        isPrime = 1
    }
    //skip even numbers
    num += 2
}
print(primeList)

Grabbing primeList[199] will grab the 200th prime number because arrays start at 0. You can combine while loops with for-in loops to calculate prime numbers.

To if or to else (if/else)

It’s important to be able to make decisions in code. It’s okay for you to be indecisive but you wouldn’t want that for your code. Let’s look at a quick example of how to make decisions in Swift:

let carInFrontSpeed = 54
if carInFrontSpeed < 55 {
    print("I am passing on the left")
} else {
    print("I will stay in this lane")
}

You use Swift’s if and else statements to make a decision based on whether a constant is less than 55. Since the integer 54 is less than the integer 55, you print the statement in the if section.

One caveat to if statements is that in some languages you can use things that are “truthy,” like 1 or a non-empty array. That won’t work in Swift. You must conform to the protocol BooleanType. To make this simple, you must use true or false. For example, here are some examples that will not work:

if 1 { // 1 in an Int and can't be converted to a boolean
    //Do something
}
var a = [1,2,3]
if a.count{ // a.count is an Int and can't be converted to a boolean
    print("YES")
}

If you want to make these examples work, you would have to convert those numbers to a Bool. For example, check out what happens when we convert some simple integers to Booleans.

print(Bool(1)) // true
print(Bool(2)) // true
print(Bool(3)) // true
print(Bool(0)) // false

If Ints can be converted into Bools, you can check for if with a truthy value if you first convert it to a Bool. Let’s rewrite our previous failing examples and make them work.

if Bool(1) { // 1 in an Int and can't be converted to a boolean
    print("Duh it works!")
}
var a = [1,2,3]
if Bool(a.count){ // a.count is an Int and can't be converted to a boolean
    print("YES")
}

We were able to check for 1 and an array count in the if statement because we first converted them to Bools.

You may also want to check multiple statements to see whether they’re true or false. You want to check whether the car in front of you slows down below 55 mph, whether there is a car coming, and whether there is a police car nearby. You can check all three in one statement with the && operator. This operator states that both the statement to its left and the one to its right must be true. Here’s what it looks like:

var policeNearBy = false
var carInLane3 = false
var carInFrontSpeed = 45
if !policeNearBy && !carInLane3 && carInFrontSpeed < 55 {
    print("We are going to pass the car.")
} else {
    print("We will stay right where we are for now.")
}

Your code will make sure that all three situations are false before you move into the next lane (the else).

Aside from the and operator, you also have the or operator. You can check to see whether any of the statements is true by using the or operator, which is written as two pipes: ||. You could rewrite the preceding statement by using the or operator. This example just checks for the opposite of what the preceding example checks for:

var policeNearBy = false
var carInLane3 = false
var carInFrontSpeed = 45
if policeNearBy || carInLane3 || carInFrontSpeed > 55 {
    print("We will stay right where we are for now.")
} else {
    print("We are going to pass the car.")
}

If any of the preceding variables is true, you will stay where you are; you will not pass the car.

Aside from just if and else, you may need to check for other conditions. You might want to check multiple conditions, one after the other, instead of just going straight to an else. You can use else if for this purpose, as shown in this example:

var policeNearBy = false
var carInLane3 = false
var carInFrontSpeed = 45
var backSeatDriverIsComplaining = true
if policeNearBy || carInLane3 || carInFrontSpeed > 55 {
    print("We will stay right where we are for now.")
} else if backSeatDriverIsComplaining {
    print("We will try to pass in a few minutes")
}else {
    print("We are going to pass the car.")
}

You can group as many of these else ifs together as you need. However, when you start grouping a bunch of else if statements together, it might be time to use the switch statement.

Switching It Up: switch Statements

You can get much more control and more readable code if you use a switch statement. Using tons of if else statements might not be as readable. Swift’s switch statements are very similar to those in other languages with extra power added in. The first major difference with switch statements in Swift is that you do not use the break keyword to stop a condition from running through each case statement. Swift automatically breaks on its own when the condition is met.

Another caveat about switch statements is that they must be absolutely exhaustive. That is, if you are using a switch statement on an int, you need to provide a case for every int ever. This is not possible, so you can use the default statement to provide a match when nothing else matches. Here is a basic switch statement:

var num = 5
switch num {
case 2:print("It's two")
case 3:print("It's three")
default:print("It's something else")
}

This tests the variable num to see whether it is 2, 3, or something else. Notice that you must add a default statement. As mentioned earlier, if you try removing it, you will get an error because the switch statement must exhaust every possibility. Also note that case 3 will not run if case 2 is matched because Swift automatically breaks for you.

You can also check multiple values at once. This is similar to using the or operator (||) in if else statements. Here’s how you do it:

var num = 5
switch num {
case 2,3,4:print("It's two") // is it 2 or 3 or 4?
case 5,6:print("It's five") // is it 5 or 6?
default:print("It's something else")
}

In addition, you can check within ranges. The following example determines whether a number is something between 2 and 6:

var num = 5
switch num {
// including 2,3,4,5,6
case 2...6:print("num is between 2 and 6")
default:print("None of the above")
}

You can use tuples in switch statements. You can use the underscore character (_) to tell Swift to “match everything.” You can also check for ranges in tuples. Here’s how you could match a geographic location:

var geo = (2,4)
switch geo {
//(anything, 5)
case (_,5):print("It's (Something,5)")
case (5,_):print("It's (5,Something)")
case (1...3,_):print("It's (1 or 2 or 3, Something)")
case (1...3,3...6):print("This would have matched but Swift already found a match")
default:print("It's something else")
}

In the first case, you are first trying to find a tuple whose first number is anything and whose second number is 5. The underscore means “anything,” and the second number must be 5. Our tuple is 2,4 so that won’t work because the second number in our tuple is 4.

In the second case, you are looking for the opposite of the first case. In this instance the first number must be 5 and the second number can be anything.

In the third case, you are looking for any number in the range 1 to 3, including 3, and the second number can be anything. Matching this case causes the switch to exit. We can use ranges to check numbers in switch statements, which makes them even more powerful.

The next case would also match, but because Swift has already found a match, it never executes. In this case we are checking two ranges.

Switch statements in Swift break on their own. If you’ve ever programmed in any other common language, you know you have to write break so that the case will stop. If you want that typical Objective-C, JavaScript functionality that will not use break by default (where the third case and fourth case will match), you can add the keyword fallthrough to the case, and the case will not break:

var geo = (2,4)
switch geo {
//(anything, 5)
case (_,5):print("It's (Something,5)")
case (5,_):print("It's (5,Something)")
case (1...3,_):
    print("It's (1 or 2 or 3, Something)")
    fallthrough
case (1...3,3...6):
    print("We will match here too!")
default:print("It's something else")
}

Now the third case and fourth case match, and you get both print statements:

It's (1 or 2 or 3, Something)
We will match here too!

Remember the value binding example from earlier? You can use this same idea in switch statements. Sometimes it’s necessary to grab values from the tuple. You can even add in a where statement to make sure you get exactly what you want. Here is the kitchen-sink example of switch statements:

var geo = (2,4)
switch geo {
case (_,5):print("It's (Something,5)")
case (5,_):print("It's (5,Something)")
case (1...3,let x):
    print("It's (1 or 2 or 3, \(x))")
case let (x,y):
    print("No match here for \(x) \(y)")
case let (x,y) where y == 4:
    print("Not gonna make it down here either for \(x) \(y)")
default:print("It's something else")
}

You might get a warning here telling you that a case will never be executed, and that is okay. This is the mother of all switch statements. Notice that the last two cases will never run. You can comment out the third and fourth switch statements to see each run. We talked about the first case and second case. The third case sets the variable x (to 4) to be passed into the print if there is a match. The only problem is that this works like the underscore by accepting everything. You can solve this with the where keyword. In the fourth case, you can declare both x and y at the same time by placing the let outside the tuple. Finally, in the last case, you want to make sure that you pass the variables into the statement, and you want y to be equal to 4. You control this with the where keyword.

Stop...Hammer Time

It’s important to have some control over your switch statements and loops. You can use break, continue, and labels to provide more control.

Using break

Using break stops any kind of loop (for, for in, or while) from carrying on. Say that you’ve found what you were looking for, and you no longer need to waste time or resources looping through whatever items remain. Here’s what you can do:

var mystery = 5
for i in 1...8 {
    if i == mystery {
        break
    }
    print(i) // Will be 1, 2, 3, 4
}

The loop will never print 5 and will never loop through 6, 7, or 8.

Using continue

Much like break, continue will skip to the next loop and not execute any code below the continue. If you start with the preceding example and switch out break with continue, you will get a result of 1, 2, 3, 4, 6, 7, and 8:

var mystery = 5
for i in 1...8 {
    if i == mystery {
        continue
    }
    print(i) // Will be 1, 2, 3, 4, 6, 7, 8
}

Using Labeled Statements

break and continue are fantastic for controlling flow, but what if you had a switch statement inside a for in loop? You want to break the for loop from inside the switch statement, but you can’t because the break you write applies to the switch statement and not the loop. In this case, you can label the for loop so that you can tell the for loop to break and make sure that the switch statement does not break:

var mystery = 5
rangeLoop: for i in 1...8 {
    switch i {
    case mystery:
        print("The mystery number was \(i)")
        break rangeLoop
    case 3:
        print("was three. You have not hit the mystery number yet.")
    default:
        print("was some other number \(i)")
    }
}

Here, you can refer to the right loop or switch to break. You could also break for loops within for loops without returning a whole function. The possibilities are endless.

  • + Share This
  • 🔖 Save To Your Account