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.
Empty Strings
Un valore di stringa vuota può essere creato come punto di partenza per una stringa più lunga. Per effettuare questa operazione, assegnare una stringa vuota letterale a una variabile o inizializzare una nuova istanza String utilizzando sintassi di inizializzazione:
var emptyString = “” // empty string literal<br></br>var anotherEmptyString = String() // initializer syntax
Entrambe le stringhe sono vuote e equivalenti tra loro.Determinare se un valore stringa è vuota controllando la sua proprietà booleana isEmpty:
if emptyString.isEmpty {<br></br>print(“String is empty”)<br></br>}
Concatenation
valori stringa possono essere sommati (o concatenati) con l’operatore di addizione (+) per creare un nuovo valore di stringa:
let string1 = “Hello”<br></br>let string2 = “ World”<br></br>var welcome = string1 + string2<br></br>// welcome now equals “Hello World”
L’operatore di assegnazione addizione (+ =) aggiunge un valore String di una variabile stringa esistente
var msg = “Hi”<br></br>msg += “ David”<br></br>// msg is now “Hi David”
String Interpolation
String interpolazione comprende i valori di un mix di costanti, variabili, letterali, e le espressioni all’interno di una stringa letterale per formare un nuovo valore Stringa. Precedere ogni elemento con una barra rovesciata, posizionare l’elemento tra parentesi, e inserirlo nella stringa letterale.
let mult = 4<br></br>let message = “(mult) times 1.5 is (Double(mult) * 1.5)”<br></br>// message is “4 times 1.5 is 6”
Nell’esempio precedente, il valore del moltiplicatore viene inserito nella stringa letterale come \ (mult). Quando l’interpolazione stringa viene valutata prima di creare la stringa effettiva, questo segnaposto viene sostituito con il valore effettivo di mult.
Più avanti nella stringa, il valore di mult appare all’interno di un’espressione più ampia all’interno della stringa letterale: \ (double(Mult) * 1.5). L’espressione calcola il valore della Double(mult) * 1.5 e quindi inserisce il risultato (6) nella stringa.
Counting Characters
Per ottenere un conteggio dei valori carattere di una stringa, utilizzare la proprietà conteggio della proprietà caratteri della stringa:
let someString = “I am learning with SoloLearn”<br></br>print(“someString has (someString.characters.count) characters”)<br></br>// prints “someString has 28 characters”
Comparing Strings
Swift offre tre opzioni per il confronto dei valori testuali: stringa e il carattere di uguaglianza,prefix equality , e suffix equality.
Utilizzare l’operatore “equal to” (==) e il “not equal to” (! =) per determinare uguaglianza di stringa e di carattere.
Utilizzare metodi hasPrefix e hasSuffix della stringa per determinare se una stringa ha un particolare prefisso o suffisso di stringa. Entrambi i metodi adottano un solo argomento di tipo String e restituiscono un valore booleano.
let s1 = “We are alike”<br></br>let s2 = “We are alike”<br></br>if s1 == s2 {<br></br>print(“These two strings are equal”)<br></br>}<br></br>// prints “These two strings are equal”
Utilizzare metodi hasPrefix e hasSuffix della stringa per determinare se una stringa ha un particolare prefisso o suffisso di stringa. Entrambi i metodi adottano un solo argomento di tipo String e restituiscono un valore booleano
Arrays
Un array è un elenco ordinato di valori dello stesso tipo, in cui lo stesso valore può apparire più volte in posizioni diverse. In Swift, il tipo di array può essere scritto in forma completa come Array <t>, in cui T rappresenta il tipo valore dell'array consentito da memorizzare. Il tipo di array può anche essere espresso in forma abbreviata, come [T].</t>
Creating an Empty Array
Creare un array vuoto di un certo tipo utilizzando la sintassi di inizializzazione.
var someInts = Int
Si noti che il tipo di variabile someInts viene dedotta per essere [Int], dal tipo di inizializzatore.
Array with a Default Value
Array di Swift fornisce anche un inizializzatore per la creazione di una array di una certa dimensione, con tutti i suoi valori impostati allo stesso valore predefinito. Si può passare a questa inizializzazione il numero di elementi da aggiungere al nuovo array (chiamato count) e un valore di default del tipo appropriato (chiamato repeatedValue)
var fourDoubles = Double<br></br>fourDoubles is of type [Double], and equals [0.0, 0.0, 0.0, 0.0]
Array Literal
Utilizzare un array letterale è un altro modo per inizializzare un array. L’array letterale è un’abbreviazione per uno o più valori scritti come collezione di array, ed è scritto come un elenco di valori, separati da virgole, parentesi quadre all’inizio e alla fine. [value 1, value 2, value 3]
The example below creates an array called shoppingList, for storing String values:
var shoppingList: [String] = [“Bread”, “Milk”]
Questo particolare array può memorizzare solo valori stringa, poichè ha String specificato come tipo di valore. A causa di inferenza di tipo di Swift, non c’è bisogno di scrivere il tipo di array. Assicurarsi di inizializzare un array letterale contenente valori della stessa tipologia. L’inizializzazione di ShoppingList sarebbe potuto essere scritto in una forma più breve:
var shoppingList = [“Bread”, “Milk”]
Tutti i valori nella matrice letterale sono dello stesso tipo, consentendo a Swift di dedurre che [String] è il typo corretto per la variabile shoppingList
La combinazione di due array esistenti con tipi compatibili utilizzando l’operatore di addizione (+) consente di creare un nuovo array. Swift deduce il type della nuova matrice in base al type dei due array combinati.
// prints "The shopping list contains 2 items." Utilizzare la proprietà booleana **isEmpty** come scorciatoia quando si desidera sapere se la proprietà conteggio è uguale a 0. if shoppingList.isEmpty {
print("The shopping list is empty.")
} else {
print("The shopping list is not empty.")
}
// prints "The shopping list is not empty."
shoppingList += ["Chocolate", "Cheese"]
// the last item has just been removed
print(item)
} In alternativa, utilizzare il metodo **enumerate ()** per iterare in una array quando è necessario l'indice intero per ogni elemento oltre al suo valore. Questo restituisce un tuple per ogni elemento dell'array che indica l'indice e il valore di quell'elemento. È possibile scomporre la tuple in costanti o variabili temporanee come parte di iterazione: for (index, value) in shoppingList.enumerate() {
print("Item \(index + 1): \(value)")
} Questo stampa l'indice e il valore degli elementi nell'array.
// the value for "LHR" has been changed Utilizzare il metodo UpdateValue di un dizionario come alternativa all'indicizzazione di quando si imposta o aggiorna il valore di una chiave. Il metodo UpdateValue restituisce il vecchio valore dopo l'esecuzione di un aggiornamento: let oldValue = airports.updateValue("New York", forKey: "NY") Subscript syntax viene utilizzato anche per recuperare un valore per una particolare chiave dal dizionario. Se il valore per la chiave richiesta non esiste, Swift restituisce un valore nil (zero): let airportName = airports["NY"] Utilizzare subscript syntax per assegnare un valore nil a una key per rimuovere una coppia key-value da un dizionario. airports["APL"] = "Apple"
airports["APL"] = nil In alternativa, il metodo removeValueForKey rimuove una coppia key-value da un dizionario, se la coppia esiste, e restituisce il valore rimosso. nil viene restituito se non esiste alcun valore. if let removedValue = airports.removeValueForKey("NY") {
print("The removed airport's name is \(removedValue).")
} else {
print("The airports dictionary does not contain a value for NY.")
}
print("\(airportCode): \(airportName)")
} Inoltre, l'accesso a proprietà delle chiavi e valori di un dizionario richiamerà una collezione iterabile di chiavi o valori del dizionario. for airportCode in airports.keys {
print("Airport code: \(airportCode)")
}
for airportName in airports.values {
print("Airport name: \(airportName)")
} Dal momento che il Dizionario di Swift non ha un ordinamento definito, utilizzare il metodo sort () sulle proprietà di key o values del dizionario per iterare le chiavi o valori in un ordine specifico.