gpt4 book ai didi

swift - 为什么调用此属性的 didSet

转载 作者:可可西里 更新时间:2023-10-31 23:44:03 25 4
gpt4 key购买 nike

protocol FooType {
var num:Int { get set }
}

class Foo: FooType {
var num: Int = 0 {
didSet {
print("Did set num")
}
}
}

class Bar {
var foo: FooType = Foo() {
didSet {
print("Did set Foo")
}
}

func changeNum(num:Int) {
foo.num = num
}
}

let bar = Bar()
bar.changeNum(5)

Did set num
Did set Foo

在此示例中,为 foo 设置属性会导致调用 Bar 的 foo 的 didSet。

我希望只有 Foo 的 num didSet 被调用。

如果我移除 Bar 的 foo 属性对 FooType 的协议(protocol)约束,它会按照我的预期运行。

protocol FooType {
var num:Int { get set }
}

class Foo: FooType {
var num: Int = 0 {
didSet {
print("Did set num")
}
}
}

class Bar {
var foo = Foo() {
didSet {
print("Did set Foo")
}
}

func changeNum(num:Int) {
foo.num = num
}
}

let bar = Bar()
bar.changeNum(5)

Did set num

如果我保持与 FooType 的一致性,但添加一个类约束 (FooType: class),它也会按预期运行。

protocol FooType: class {
var num:Int { get set }
}

class Foo: FooType {
var num: Int = 0 {
didSet {
print("Did set num")
}
}
}

class Bar {
var foo: FooType = Foo() {
didSet {
print("Did set Foo")
}
}

func changeNum(num:Int) {
foo.num = num
}
}

let bar = Bar()
bar.changeNum(5)

Did set num

如果我完全删除协议(protocol)并使 Foo 成为一个结构而不是一个类,我们将返回调用两个 setter 的情况。

struct Foo {
var num: Int = 0 {
didSet {
print("Did set num")
}
}
}

class Bar {
var foo = Foo() {
didSet {
print("Did set Foo")
}
}

func changeNum(num:Int) {
foo.num = num
}
}

let bar = Bar()
bar.changeNum(5)

Did set num
Did set Foo

在将 Foo 更改为结构的情况下,我可以理解为什么会这样……它在 swift 文档中提到了它,因为结构是一种值类型,它会生成一个副本,等等(虽然我没想到一开始)。

但其他情况我没有得到...

最佳答案

你可以通过让 FooType 符合 AnyObject 来解决这个问题

protocol FooType: AnyObject {
var num:Int { get set }
}

关于swift - 为什么调用此属性的 didSet,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36568261/

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