swift - 避免重复属性方法
问题描述
我有这种带有通知令牌属性设置器的重复模式
一旦属性设置为 nil,then 也会从观察中移除
如何用轻量级解决方案替换和避免属性方法的代码重复?
var nt1: Any? {
willSet {
if let nt1 = nt1 {
NotificationCenter.default.removeObserver(nt1)
self.nt1 = nil
}
}
}
var nt2: Any? {
willSet {
if let nt = nt2 {
NotificationCenter.default.removeObserver(nt)
self.nt2 = nil
}
}
}
var nt3: Any? {
willSet {
if let nt = nt3 {
NotificationCenter.default.removeObserver(nt)
self.nt3 = nil
}
}
}
解决方案
您可以创建一个@propertyWrapper。它是在 Swift 5.1 中引入的
@propertyWrapper
struct UnsubscribeOnNil<Value: Any> {
init(wrappedValue: Value?) {
self.value = wrappedValue
}
private var value: Value?
var wrappedValue: Value? {
get { value }
set {
if newValue == nil, let oldValue = value {
NotificationCenter.default.removeObserver(oldValue)
}
value = newValue
}
}
}
并将其用于属性:
@UnsubscribeOnNil var nt1: Any?
@UnsubscribeOnNil var nt2: Any?
@UnsubscribeOnNil var nt3: Any?
推荐阅读
- javascript - 如何阻止可扩展的 Material UI 卡片同时打开?
- google-kubernetes-engine - 是否可以通过 GKE 入口配置 Google Cloud 内部 TCP/UDP 负载均衡器?
- css - 如何在打字稿项目中添加缩小的引导文件?
- kubernetes - GKE BackendConfig 不适用于 customRequestHeaders
- python - 如何解决:TypeError:fit() 缺少 1 个必需的位置参数:'y'
- android - android studio中的模糊元素
- python - 模型实例未呈现到模板中
- javascript - 如何使用 javascript 更改 JSON 文件
- postgresql - 如何将用户选择的 csv 文件导入 ASP.NET Core MVC 上的数据库
- python - 如何在odoo中以真正的字母顺序(不区分大小写)排序顺序获取记录?