- Mastering macOS Programming
- Stuart Grimshaw
- 194字
- 2021-07-02 22:54:20
Iterating with for loops
Firstly, if we need to perform a loop a specific number of times, we can simply iterate over a range:
for i in 1...10
{
print(i)
}
This loop will then print the numbers 1 up to and including 10.
If we don't explicitly care about how many times a loop takes place, but need to iterate over an entire Array, we can iterate directly over it, using the following syntax:
let arr = [1, 1, 2, 3, 5]
for i in arr
{
print(i)
}
If we need to know the index of each object in the array, we can apply its enumerated method, which returns to us a sequence of (index, value) tuples:
for (index, i) in arr.enumerated()
{
print("The value at index \(index) is \(i)")
}
A similar syntax exists for Dictionary objects:
let dict = ["a": 1, "b": 2, "c": 3]
for (letter, position) in dict
{
print(letter, position)
}
We can also iterate over Set objects:
let set:Set = [2,3,5]
for n in set
{
print(n)
}
If one of those doesn't fulfil your needs, you can always roll your own using while and repeat.