gpt4 book ai didi

swift - 闭包捕获值类型

转载 作者:行者123 更新时间:2023-11-30 10:31:32 26 4
gpt4 key购买 nike

我在下面运行了代码,我期望 print()s 会返回零作为 is 值类型,并且会是复制到闭包中,但似乎它们是通过引用传递的。对于 Objective-C,我们必须使用 __block 属性来实现这样的行为。有什么解释为什么会这样吗?

        var i = 0
var s = "0"

print(i)
print(s)

let c = {
i = 1
s = "11"
}

c()

print(i)
print(s)

输出为:

1
11

最佳答案

Swift 中的闭包始终通过引用捕获变量。它相当于 C/Objective-C block ,所有捕获的变量都是 __block

关于swift - 闭包捕获值类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59117867/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com