gpt4 book ai didi

Swift:总是在 inout 上复制?

转载 作者:搜寻专家 更新时间:2023-10-31 22:14:45 24 4
gpt4 key购买 nike

我编写了一个用于序列化模型数据的简单库,后来意识到我在只读取数据时正在写入数据。我能够将问题减少到以下 Playground 片段:

class Foo {
init() { name = "test" }
var name:String { didSet { print("setting name: \(self.name)") }}
}


func map(inout foo:String) {
print("writing value: \(foo)")
}

var foo:Foo = Foo()
map(&foo.name)

结果(对我来说)出乎意料:

writing value: test

setting name: test

我重新阅读了关于 inout 参数的部分,但没有看到明确提及复制语义。我的直觉是,如果没有其他代码这样做,编译器会期望该值被覆盖,并使用初始值自行覆盖。

这是否符合预期,还是编译器错误?在我看来,这是不符合直觉的行为。我没想到会有作业,除非它源 self 的代码——但事实并非如此。

为了说明什么是显而易见的,上面的代码片段不需要 inout 参数,但我一直在使用通用接口(interface)进行读写。

最佳答案

我代表 Joe Groff 发帖,Swift 编译器开发人员,on Twitter (见回复)。他很好地回答了我提到这个问题的推文。

他说:

Inout has value-result semantics. The didSet receives the modified value at the end of the inout. It only optimizes to pass-by-reference if the difference is unobservable (modulo invalid aliasing). The Swift book is supposed to be updated with this info too.

关于Swift:总是在 inout 上复制?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32974927/

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