gpt4 book ai didi

swift - Getter 意外地第二次调用 inout 参数

转载 作者:行者123 更新时间:2023-11-28 08:38:02 25 4
gpt4 key购买 nike

我正在学习 Swift,我不明白为什么这段代码打印出冗余输出:

class A {}
var x: A {
set { print("set") }
get {
print("get")
return A()
}
}
func f(inout y: A) { print("f") }
f(&x)

结果是:

get
f
set
get

为什么最后到这里?如果我在 f 中添加另一个 inout 参数:

class A {}
var x: A {
set { print("set") }
get {
print("get")
return A()
}
}
func f(inout y: A, inout z: Int) { print("f") }
var z = 10
f(&x, z:&z)

新的结果是:

get
f
set

你能清理我吗?

最佳答案

我猜你是在 Playground 上写这段代码!?

如果将其放入常规项目并在模拟器上运行,则不会看到该行为。
它只发生在 Playground 上

在设备上两种方法都打印出预期的结果

get
f
set


说明:

Playground 执行看起来像这样:

enter image description here

注意到右侧打印的最后一行中的 A 了吗? Playground 尝试显示 x 的值,为了显示它,它访问了它的 getter!如果您有多个参数,Xcode 不会尝试打印任何内容 -> 添加第二个参数会导致 Xcode 无法获取任何值。

关于swift - Getter 意外地第二次调用 inout 参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37205464/

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