swift - 避免重复属性方法

标签 swift cocoa cocoa-touch

我有一个带有通知 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/

相关文章:

ios - UIWebView 显示本地加载图像的白屏

macos - OSX/macOS - 如何将 xib 迁移到 Storyboard

macos - 为什么沙箱不能阻止我的应用程序访问任意 URL?

swift - iOS 图表饼图大小

objective-c - Core Data - 通过 URI 获取托管对象

macos - 检测用户正在 chrome/firefox/safari 中查看的 url

iphone - 并加载 NIB/XIB 文件?

iOS分享扩展-发送大视频

iphone - 如何限制 5 个 UITextFields 中的字符数量

ios - getDocuments() 函数多次获取相同的数据