斯威夫特:总是在 inout 上复制? [英] Swift: always copies on inout?

查看:36
本文介绍了斯威夫特:总是在 inout 上复制?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I wrote a simple library for serializing model data and later realized I was getting writes to my data when I was only reading. I was able to reduce the problem to the following playground snippet:

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)

结果(对我而言)出乎意料:

The result is (to me) unexpected:

写作价值:测试

设置名称:测试

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

I have re-read the section on inout parameters but saw no explicit mention of copy semantics. My hunch is that the compiler is expecting the value to be overwritten and does so itself with the initial value, if no other code does so.

这似乎是预期的,还是编译器错误?在我看来,这是一种不直观的行为.我并不期待分配,除非它来自我的代码 - 它不是.

Does this seem expected, or a compiler bug? In my humble opinion, it is unintuitive behavior. I was not expecting an assignment, unless it originated from my code - which it did not.

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

To state what is hopefully obvious, the code snippet above does not need the inout param, but I had been using a common interface for reading and writing.

推荐答案

我代表 Joe Groff,一位 Swift 编译器开发者,在 Twitter 上(见回复).他很友好地回答了我提到这个问题的推文.

I'm posting this on behalf of Joe Groff, a Swift compiler developer, on Twitter (See replies). He was very nice in answering my Tweet mentioning this question.

他说:

Inout 具有值-结果语义.didSet 在 inout 的末尾接收修改后的值.如果差异不可观察(模无效别名),它仅优化为传递引用.Swift 书籍也应该使用此信息进行更新.

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.

这篇关于斯威夫特:总是在 inout 上复制?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆