Control Flow & Collection Flashcards
Conditional statements (istruzioni condizionali)
Una dichiarazione condizionale esegue in determinate condizioni una certa porzione di codice. Ad esempio, è possibile eseguire un codice particolare quando si verifica un errore o visualizzare un messaggio quando un valore supera una determinata linea di base. Per impostare le condizioni, utilizzare le istruzioni if o switch
The if Statement
The most basic if statement contains a single if condition, and executes a set of statements only if that condition is true:
var temp = 25<br></br>if temp <= 30 {<br></br>print(“It’s cold.”)<br></br>}
You can specify additional conditions by chaining together multiple if statements.
if cardValue == 11 {<br></br>print(“Jack”)<br></br>} else if cardValue == 12 {<br></br>print(“Queen”)<br></br>}<br></br>else {<br></br>print(“Not found”)<br></br>}
You can add as many else-if statements as needed.
The switch Statement
Use the switch statement as an alternative to the if statement for multiple potential states. The switch statement compares a value with several possible matching patterns, executing a block of code using the first matching pattern.
Each case begins with the keyword case:
switch distance {<br></br>case 0:<br></br>print(“not a valid distance”)<br></br>case 1,2,3,4,5:<br></br>print(“near”)<br></br>default:<br></br>print(“too far”)<br></br>}
A single case can contain multiple values, as in our example above. It can also contain ranges, using the range operators.
Every switch statement must be exhaustive, i.e. take every possible value into consideration. In cases in which it is not appropriate to provide a switch case for every possible value, you can define a default catch-all case to cover any values that are not explicitly addressed. Indicate the catch-all case by using the keyword default. This always appears last.
Swift doesn’t require break statements, but will still accept one to match and ignore a particular case, or to break out of a matched case before that case has completed its execution.
Where
The where clause checks for additional conditions.
let myPoint = (1, -1)<br></br>switch myPoint {<br></br>case let (x, y) <strong>where</strong> x == y:<br></br>print(“((x), (y)) is on the line x == y”)<br></br>case let (x, y) <strong>where</strong> x == -y:<br></br>print(“((x), (y)) is on the line x == -y”)<br></br>case let (x, y):<br></br>print(“((x), (y)) is just some arbitrary point”)<br></br>}
The three switch cases declare placeholder constants x and y, which temporarily take on the two values from myPoint, creating a dynamic filter as part of a where clause. The switch case matches the current value of point only if the where clause’s condition evaluates to true for that value.
The final case matches all possible remaining values; a default case is not necessary to have an exhaustive switch statement.
The while Loop
A while loop performs a set of statements until a condition becomes false. These kinds of loops are best used when the number of iterations is not known before the first iteration begins.
while evaluates its condition at the start of each pass through the loop.
while a < b {<br></br>print(a)<br></br>a++<br></br>}
The code will execute until the a++ statement renders a < b as false.
Repeat-While
The repeat-while loop is the alternate while loop. It first makes a single pass through the loop block, then considers the loop’s condition, and repeats the loop until the condition shows as false.
repeat {<br></br>x–<br></br>} while x > 0
Swift’s repeat-while loop is similar to a do-while loop in other languages.
The for-in Loop
Use the for-in loop to iterate over a sequence, such as ranges of numbers, items in an array, or characters in a string.
The following example prints the first few entries in the five-times-table:
for index in 1…5 {<br></br>print(“(index) times 5 is (index * 5)”)<br></br>}<br></br>// 1 times 5 is 5<br></br>// 2 times 5 is 10<br></br>// 3 times 5 is 15<br></br>// 4 times 5 is 20<br></br>// 5 times 5 is 25
The index variable is set at the first value in the range (1). The statements within the for loop are then executed in sequence, through the final item in the range (5).
The for Loop
The for loop cycles through a set of statements until a specific condition is met. A typical for loop runs a counter at the end of each loop, and consists of three parts: counter initialization, condition, and increment:
<sub>for var index = 0; index < 3; ++index {<br>print("index is \(index)")<br>}</sub> <sub>// index is 0<br>// index is 1<br>// index is 2</sub>
Semicolons are inserted to define the loop’s three parts.
The loop is executed as follows:
- Upon entering the loop, the initialization expression is evaluated once, establishing the loop’s constants and/or variables.
- If the condition expression is found to be true when evaluated, the statements in braces are executed to continue code execution.
- The increment expression is evaluated once all statements have been executed, and code execution returns to Step 2.
Constants and variables in the initialization expression (such as var index = 0) are only valid within the for loop itself. To retrieve the final value of index after the loop ends, you must declare index before the loop begins.
Control Transfer
Control transfer statements alter the code execution by transferring control from one piece of code to another. Swift’s four control transfer statements are continue, break, fallthrough, and return
Continue
The continue statement stops the loop, then restarts it at the beginning of its next cycle. It says “I am done with the current loop iteration” without leaving the loop altogether.
The example below shows how to use the continue statement to skip over even numbers.
for num in 1…10 {<br></br>if num%2 == 0 {<br></br>continue<br></br>}<br></br>print(num)<br></br>}
A for loop with a condition and an incrementer still evaluates the incrementer after the continue statement is initiated. The loop itself continues to work as usual; only the code within the loop’s body is skipped.
Break
Use the break statement to immediately end the execution of an entire control flow statement. Also, the break statement is used within a switch statement or a loop statement to terminate its execution sooner than would otherwise be the case.
Break in a Loop Statement
When a break statement is used within a loop statement, the loop's execution immediately stops. Control transfers to the first line of code following the loop's closing brace (}). The current iteration's remaining code is skipped, and no further iterations of the loop are initiated. For example, you can have a loop that breaks out when the value of a becomes less than that of b: <sub>var b = 7<br>var a = 10<br>while a > 0 {<br>if(a < b) {<br>break<br>}<br>a--<br>}</sub>
Break in a Switch Statement
A break causes a switch statement to end its execution immediately, and transfers control to the first line of code that follows the switch statement’s closing brace (}).
var a = 5<br></br>var letter = “X”<br></br>switch a {<br></br>case 1:<br></br>letter = “A”<br></br>case 2:<br></br>letter = “B”<br></br>default:<br></br>break<br></br>}
This example breaks out of the switch statement as soon as the default case is matched.
Always use a break statement to ignore a switch case.
Fallthrough
In Swift, switch statements do not fall through the bottom of each case into the next. Instead, the entire switch statement completes its execution when the first matching case is completed.
By contrast, C requires insertion of an explicit break statement at the end of every switch case to prevent fallthrough. By eliminating default fallthrough, Swift allows for more concise and predictable switch statements in comparison with C, and thus avoids inadvertently executing multiple switch cases.
In cases that require C-style fallthrough behavior, use the fallthrough keyword on a case-by-case basis. The example below uses fallthrough to create a number’s textual description.
let myInt = 5<br></br>var desc = “The number (myInt) is”<br></br>switch myInt {<br></br>case 2, 3, 5, 7, 11, 13, 17, 19:<br></br>desc += “ a prime number, and also”<br></br>fallthrough<br></br>default:<br></br>desc += “ an integer.”<br></br>}<br></br>print(desc)
This prints “The number 5 is a prime number, and also an integer.”
If myInt’s value is one of the prime numbers in the list, text noting that the number is prime is appended to the end of the description. The fallthrough keyword then causes it to “fall into” the default case.
The fallthrough keyword does not check case conditions in the switch case into which execution falls. As with C’s standard switch statement behavior, the fallthrough keyword moves code execution directly to the statements inside the next (or default) case block.
Strings
Una stringa è un insieme ordinato di caratteri, come “Ciao, mondo” o “SoloLearn”. Stringhe Swift sono rappresentate dal tipo String, che a sua volta rappresenta un insieme di valori di tipo carattere.
I valori stringa predefiniti possono essere inclusi nel codice come stringhe letterali, o sequenze fisse di caratteri testuali all’interno di virgolette doppie (“”). Utilizzare una stringa letterale come valore iniziale per una costante o variabile.
let someString = “Some string literal value”
Poiché è inizializzato con un valore letterale di stringa, Swift deduce un tipo di String per la costante someString.