[英]Swift forEach with assignment inside the block
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]它不会永远循环,而是打印 1、2 和 3,然后数组有 6 个元素:[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?块内的数组是我调用
.append(17)
时数组的副本,对吗? And then after the loop it's assigned to the array var?然后在循环之后将其分配给数组 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.
当你创建一个 forEach 时,第二个答案看起来更准确,当前数组的副本被创建并循环遍历它的元素。
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如果您在操场上运行以下代码,您将得到 output 显示在循环的每个循环中添加到主数组的元素
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:第一个是准确的并且工作正常,但您必须将您的
arrayCopy
初始化为一个空数组,如下所示:
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.这将为您提供与您已经将 output 添加到您的阵列中相同的 output ,但这仅在您想要复制并将其放入原始阵列时才有效。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.