首页 > 解决方案 > 避免重复属性方法

问题描述

我有这种带有通知令牌属性设置器的重复模式

一旦属性设置为 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
        }
    }
}

标签: swiftcocoacocoa-touch

解决方案


您可以创建一个@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?

推荐阅读