Range Over Built in Swift
Range iterates over elements in a variety of built-in data structures. Let’s see how to use range
with some of the data structures we’ve already learned.
Here we use range
to sum the numbers in a slice. Arrays work like this too.
let nums = [2, 3, 4]
var sum = 0
for num in nums {
sum += num
}
print("sum:", sum)
range
on arrays and slices provides both the index and value for each entry. Above we didn’t need the index, so we ignored it with the blank identifier _
. Sometimes we actually want the indexes though.
for (i, num) in nums.enumerated() {
if num == 3 {
print("index:", i)
}
}
range
on map iterates over key/value pairs.
let kvs = ["a": "apple", "b": "banana"]
for (k, v) in kvs {
print("\(k) -> \(v)")
}
range
can also iterate over just the keys of a map.
for k in kvs.keys {
print("key:", k)
}
range
on strings iterates over Unicode code points. The first value is the starting byte index of the rune
and the second the rune
itself.
for (i, c) in "go".enumerated() {
print(i, c)
}
To run the program, put the code in main.swift
and use swiftc
to compile and run it.
$ swiftc main.swift -o main
$ ./main
sum: 9
index: 1
a -> apple
b -> banana
key: a
key: b
0 g
1 o
Next example: Pointers.