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

标签 swift

您好,我写的是关于 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/

相关文章:

ios - 使用 Swift 将 JSON 或 CSV 数据导入 Firestore

ios - 防止攻击者反编译 iOS 应用程序并获取数据库访问权限

ios - 如何通过 Carthage 在 Xcode 中编辑或安装框架文件?

ios - 具有嵌套队列的串行调度队列

ios - 如何从 url 链接设置左侧导航栏按钮图像?

ios - 更改录音的音高

ios - 在 xcode 中的功能下找不到热点

ios - 如何在 map 中标记注释并在选择注释时获取标记值

swift - 使用 iPhone 连接到在 Mac 上运行的 vapor 服务器

swift - 如何在 swiftui 中强制 View 更新 onAppear