Let's say I have this
var array = [1,2,3]
array.forEach {
array.append(17)
print($0)
}
It will not loop forever, instead it will print 1, 2 and 3 and afterwards the array has 6 elements: [1,2,3,17,17,17]
How can this be understood?
the array inside the block is a copy of the array the moment i call .append(17)
, right? And then after the loop it's assigned to the array var? Or is the copy made before hand?
which is actually what is going on?
This:
var array = [1,2,3]
var arrayCopy: [Int]
array.forEach {
arrayCopy.append(17)
print($0)
}
array = arrayCopy
or this:
var array = [1,2,3]
var arrayCopy = array
arrayCopy.forEach {
array.append(17)
print($0)
}
Or something else?
Intersting observation. Second answer looks more accurate when u create a forEach a copy of current array is created and looped through it's elements.
var array = [1,2,3]
var arrayCopy = array
arrayCopy.forEach {
array.append(17)
print($0)
}
If u run following code in playground u will get output showing element added to main array for each cycle of the loop
var array = [1,2,3]
array.forEach {_ in
array.append(17)
print(array)
}
//You will get following output
//[1, 2, 3, 17]
//[1, 2, 3, 17, 17]
//[1, 2, 3, 17, 17, 17]
The first one is accurate and works fine but you have to initialize your arrayCopy
as an empty array like below:
var array = [1,2,3]
var arrayCopy: [Int] = []
array.forEach {
arrayCopy.append(17)
print($0)
}
array = arrayCopy
Which will give you the same output as you already added the output into your array but this Valid only if you wanna make a copy and put it in your original array.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.