swift – 在设置x的属性时,将setSet / didSet调用容器的存储属性x

我观察到那种我不太了解的行为.在操场上执行此代码时:

protocol Testp {
    var notes: String { get set }
}

class Testc: Testp {
    var notes: String = "x"
}

class TestContainer {
    var test: Testp = Testc() {
        willSet {
            print("willSet")
        }
        didSet {
            print("didSet")
        }
    }
}

var testContainer = TestContainer()
print(testContainer.test.notes) // prints "x"

// this triggers a willSet+didSet call on TestContainer's
// stored property,even though "test" is not changed in testContainer
testContainer.test.notes = "y"

print(testContainer.test.notes) // prints "y"

如上所述,即使未设置属性本身,也会调用willSet和didSet块.

另一方面,如果我将协议更改为类型类如下

protocol Testp: class {
    var notes: String { get set }
}

然后结果就像我期望的那样(即没有调用willSet / didSet).

这种行为的原因是什么?

我在XCode 7.3上运行它.

更新:仍在XCode 9.2 / Swift 4中

解决方法

这是因为Testp很容易成为类或结构.如果它是一个结构,那么分配testContainer.test.notes =“y”将创建一个全新的Testp实现实例.另一方面,通过制作协议Testp:class,你明确地告诉对笔记的分配不会改变测试.

考虑一个功能

func doSomething(_ container: TestContainer) {
    testContainer.test.notes = "y"
}

你不知道在这函数中如何使用类或结构配置TestContainer.我想迅速的团队认为总是提高意志/ didChange不那么混乱behaIoUr就是这种情况.

相关文章

软件简介:蓝湖辅助工具,减少移动端开发中控件属性的复制和粘...
现实生活中,我们听到的声音都是时间连续的,我们称为这种信...
前言最近在B站上看到一个漂亮的仙女姐姐跳舞视频,循环看了亿...
【Android App】实战项目之仿抖音的短视频分享App(附源码和...
前言这一篇博客应该是我花时间最多的一次了,从2022年1月底至...
因为我既对接过session、cookie,也对接过JWT,今年因为工作...