Loops and String Interpolation

Swift has all the control flow statements that you may be familiar with from other languages: if-else, while, for, for-in, repeat-while, and switch. Even if they are familiar, however, there may be some differences from what you are accustomed to. The key difference between these statements in Swift and in C-like languages is that while enclosing parentheses are not necessary on these statements’ expressions, Swift does require braces on clauses. Additionally, the expressions for if and while-like statements must evaluate to a Bool.

Swift does not have the traditional C-style for loop that you might be accustomed to. Instead, you can accomplish the same thing a little more cleanly using Swift’s Range type and the for-in statement:

let range = 0..<countingUp.count
for i in range {
    let string = countingUp[i]
    // Use 'string'
}

The most direct route would be to enumerate the items in the array themselves:

for string in countingUp {
    // Use 'string'
}

What if you wanted the index of each item in the array? Swift’s enumerated() function returns a sequence of integers and values from its argument:

for (i, string) in countingUp.enumerated() {
    // (0, "one"), (1, "two")
}

What are those parentheses, you ask? The enumerated() function returns a sequence of tuples. A tuple is an ordered grouping of values similar to an array, except each member may have a distinct type. In this example the tuple is of type (Int, String). We will not spend much time on tuples in this book; they are not used in iOS APIs because Objective-C does not support them. However, they can be useful in your Swift code.

Another application of tuples is in enumerating the contents of a dictionary:

let nameByParkingSpace = [13: "Alice", 27: "Bob"]

for (space, name) in nameByParkingSpace {
    let permit = "Space (space): (name)"
}

Did you notice that curious markup in the string literal? That is Swift’s string interpolation. Expressions enclosed between ( and ) are evaluated and inserted into the string at runtime. In this example you are using local variables, but any valid Swift expression, such as a method call, can be used.

To see the values of the permit variable for each iteration of the loop, first click on the circular Show Result indicator at the far right end of the results sidebar for the line let permit = "Space (space): (name)". You will see the current value of permit under the code. Control-click on the result and select Value History (Figure 2.5). This can be very useful for visualizing what is happening in your playground code’s loops.

Figure 2.5  Using the Value History to see the results of string interpolation

Screenshot shows a portion of the Playground editor and output area illustrating the use of Value History.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset