Continuation of Hacking With Swift 100 Days of Swift
Day 4 - Looooooooops
- For loops
For loops are done on a python way (maybe swift did it first?) but without the required indentation. So if you want to loop through [1,2,3,4] you'd do:
for number in [1,2,3,4] { print(number) }
PS: Discard (the underscore _ ) is accepted if you don't want/need the actual variable
While loops
Nothing fancy to see hereRepeat Loops
Basically do whilesBreaking and skipping in loops
While the keywordcontinue
is just your everyday reserved word, breaks are really interesting.
Swift supports something called "labeled statements". Imagine the following nested loop:
for option1 in options {
for option2 in options {
// do code here
}
}
Like in other languages, if we use the keyword break
it will exit the inner loop only, inside a function we could add a return but that's if we are inside a function, so how do we exit the parent? well you give it a label and then you tell swift to break label_name;
example:
outerLoop: for option1 in options {
for option2 in options {
break outerLoop;
}
}
Pretty neat in my opinion.
Top comments (1)
PS: Search how do I format code with correct indentation later