gpt4 book ai didi

swift - 如何将枚举与属性观察器(didSet、willSet)一起使用?

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

您好,我写的是关于 https://appventure.me/2015/10/17/advanced-practical-enum-examples/#sec-4-2 的帖子

如何在属性的 didSet 内的观察者模式中使用枚举?我尝试了各种方法,但对我来说意义不大。

有人可以举例说明吗?我正在尝试找出答案,因为该解决方案可能很有趣并且有助于保持代码整洁。

这是我正在谈论的帖子的摘录:

Observer Pattern

There're various ways of modelling observation in Swift. (...) the didSet syntax makes it easy to implement simple observation. Enums can be used here in order to make the type of change that happens to the observed object clearer. Imagine collection observation. If we think about it, we only have a couple of possible cases: One or more items are inserted, one or more items are deleted, one or more items are updated. This sounds like a job for an enum:

enum Change {
case Insertion(items: [Item])
case Deletion(items: [Item])
case Update(items: [Item])
}

Then, the observing object can receive the concrete information of what happened in a very clean way. This could easily be extended by adding oldValue and newValue, too.

谢谢

最佳答案

我认为这篇文章打算将句子分开阅读,因为它是关于观察的通用部分。 didSet 与简单的实例变量一起使用,他们提议的枚举将用于包含在集合中观察到的更改的详细信息。枚举会很有用,因为您可以打开类型,然后使用内容来了解​​该更改的详细信息。

你可以有一个简单的实例变量,这样枚举值就可以用一些这样的变化信息来设置,但它不合逻辑且困惑,这不是一个好的方法。枚举更适合自定义观察,您可以在其中定义观察者的回调,从而控制传递的变量。

关于swift - 如何将枚举与属性观察器(didSet、willSet)一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36284008/

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