Swift:捕获列表
var array = [() -> ()]()
var count = 0
var index = 0
while index < 5 {
array.append {
print("count: \(count)")
print("index: \(index)")
}
count += 1
index += 1
}
array[0]()
array[4]()
输出:
数量:5
指数:5
数量:5
索引:5
相同情况但有一些变化:
var array = [() -> ()]()
var count = 0
for index in 0..<5 {
array.append {
print("count: \(count)")
print("index: \(index)")
}
count += 1
}
array[0]()
array[4]()
输出:
数量:5
索引:0
数量:5
index: 4
Count
值在这两种情况下都是相同的,因为我们没有显式捕获它,即 5
- 在第一种情况下使用全局
index
变量并且结果是最后递增的值,即 5 和 5。 - 在第二种情况下,使用了 for 循环的
index
,值分别为 0 和 4。
确切的区别是什么?
var array = [() -> ()]()
var count = 0
var index = 0
while index < 5 {
array.append {
print("count: \(count)")
print("index: \(index)")
}
count += 1
index += 1
}
array[0]()
array[4]()
Output:
count: 5
index: 5
count: 5
index: 5
Same case but with some changes:
var array = [() -> ()]()
var count = 0
for index in 0..<5 {
array.append {
print("count: \(count)")
print("index: \(index)")
}
count += 1
}
array[0]()
array[4]()
Output:
count: 5
index: 0
count: 5
index: 4
Count
value would be the same in both the cases as we are not explicitly capturing it, i.e 5
- In the first case global
index
variable is used and the result is the last incremented value i.e. 5 and 5 - In the second case for loop's
index
is used and the value is 0 and 4 respectively.
What is the exact difference?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

发布评论
评论(2)
我的鱼塘能养鲲2025-01-24 01:28:23
我调试了该代码,因为它看起来有点奇怪,但让我告诉您,追加和增量行运行良好,当您调用 array0 和 array4 时,调试器将转到append{} 的主体并打印这些变量。并从最容易访问的范围捕获这些变量。因此,在第一种情况下,它将从函数体的范围中捕获计数和索引的值实际上是新的 5 和 5。
在第二种情况下,它将尝试捕获是否有变量 count 和索引已初始化,它将找到 count 但不会找到,因此它将检查数组主体,并在那里找到第一个索引中为 0 的实际值,第 5 个索引中的 4。
这就是我能解释的全部,抱歉英语不好
~没有更多了~
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
在第一个示例中,
index
是var
声明的,并且每次使用的变量都是相同的,在第二个示例中,它是let
声明的例如,它是每次迭代的for
循环范围内存在的index
的新实例In the first example
index
isvar
declared and it is the same variable used each time, in the second it islet
declared so in the second example it is a new instance ofindex
that exists in the scope of thefor
loop for each iteration