I have this repeating pattern with setters for notification token property
Once the property is set to nil, then is also removed from observation
how to replace and avoid this code repetition of property methods with a lightweight solution?
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
}
}
}
You can create a @propertyWrapper. It was introduced with 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
}
}
}
And use it for properties:
@UnsubscribeOnNil var nt1: Any?
@UnsubscribeOnNil var nt2: Any?
@UnsubscribeOnNil var nt3: Any?