我有一个带有通知 token 属性 setter 的重复模式
一旦属性设置为 nil,那么也会从观察中删除
如何用轻量级解决方案替换并避免属性方法的代码重复?
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?
关于swift - 避免重复属性方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59837825/