I'm attempting to write simple Swift for
loops like so:
for i in [0...10] {
// ...
}
for i in [0..<10] {
// ...
}
These for-in
loops over a range are important due to the absence of classic C-style for
loops in Swift. I am attempting to enumerate over any array of Ints built via Swift's ...
and ..<
syntax.
Note that if I construct an array of Ints "manually" rather than use [...]
or [..<]
, it works fine:
for i in [0, 1, 2, 3, 4, 5] {
// this works fine
}
But the [0..<5]
loops produce errors basically any time I try to use the value i
:
let _ = i + 1
Here are the errors I get:
- Binary operator `'+'` cannot be applied to operands of type `'ClosedRange<Int>'` and `'Int'`
- Binary operator `'+'` cannot be applied to operands of type `'Range<Int>'` and `'Int' `
I have also tried this:
let _ = String(i)
And I get:
Ambiguous reference to initializer `'init(_:)'`
Why are these simple for-in
loops not working?
Why are the errors referencing Range
and ClosedRange
? I am expecting an Int
.
Swift ranges are written as 0...10
, not [0...10]
.
[0...10]
creates a single-item array. The first item in the array is a 0...10
range.
Using for i in [0...10]
thus iterates over that single-item array, not the range itself. The iterated value i
will be of type Range
or ClosedRange
.
To iterate over each Int
in the range, as you expect to be doing, use the range 0...10
without the brackets:
for i in 0...10 {
// ...
}
for i in 0..<10 {
// ...
}
https://docs.swift.org/swift-book/LanguageGuide/ControlFlow.html
You can also use for-in loops with numeric ranges. This example prints the first few entries in a five-times table:
for index in 1...5 { print("\(index) times 5 is \(index * 5)") }
The sequence being iterated over is a range of numbers from 1 to 5, inclusive, as indicated by the use of the closed range operator
(...)
.