Search code examples
swiftfor-loopvariablesconstants

Is defining a constant within a for-loop possible in Swift?


Just beginning to learn Swift and stumbled across the following code in a book:

for i in 0..<n {
    let x = start + delta * Double(i)
    result += [fn(x)]
}
return result

What puzzles me is, that x seems to be defined as a constant, but within a for loop, which should not be possible as it changes its value.

I was expecting something like:

for i in 0..<n {
    var x = start + delta * Double(i)
    result += [fn(x)]
}
return result

Solution

  • … as it changes its value.

    It does not change the value, the local constant is (re)created in each iteration and thrown away in the closing brace line.

    It changes the value therefore it must be a variable with this syntax where it's declared before the loop

    var x : Double
    for i in 0..<n {
        x = start + delta * Double(i)
        result += [fn(x)]
    }
    return result