Is there a way to refer outter variable in for
loop?
For instance
var output = ""
var data = ["a", "b", "c"]
let size = data.count
var i = 0
//
// How can I make this loop referring to variable "var i = 0"?
//
for i in 0..<size-1 {
output.append(data[i])
output.append("\n")
}
//
// Will not be executed because i remains 0
//
if (i == size-1) {
output.append(data[i])
}
The only workaround I have found is
var output = ""
var data = ["a", "b", "c"]
let size = data.count
var i = 0
while (i < size-1) {
output.append(data[i])
output.append("\n")
i = i 1
}
if (i == size-1) {
output.append(data[i])
}
I was wondering, is there a way to make Swift for loop refer to outter variable?
CodePudding user response:
You can keep roughly the same syntax by using a different variable name within the for
loop and then assigning it to the outer variable.
In your example, naming the variable i
will shadow the outer variable (as mentioned in the comments) within the scope of the for
loop, making the outer variable inaccessible in the scope of the for
loop.
There's currently no syntax in Swift to force a for
loop's current value to bind to an existing variable.
var output = ""
var data = ["a", "b", "c"]
let size = data.count
var i = 0
for j in 0..<size-1 {
i = j
output.append(data[i])
output.append("\n")
}
if (i == size-1) {
output.append(data[i])
}
CodePudding user response:
If you don't want to use built-in function then you can check where it is less than the last index. As-
for i in 0..<size-1 {
output.append(data[i])
if i < size-1 {
output.append("\n")
}
}