小编rbe*_*een的帖子

相当于在 Swift Combine 中使用 @Published 的计算属性?

在命令式 Swift 中,通常使用计算属性来提供对数据的便捷访问,而无需复制状态。

假设我有这个类用于命令式 MVC 使用:

class ImperativeUserManager {
    private(set) var currentUser: User? {
        didSet {
            if oldValue != currentUser {
                NotificationCenter.default.post(name: NSNotification.Name("userStateDidChange"), object: nil)
                // Observers that receive this notification might then check either currentUser or userIsLoggedIn for the latest state
            }
        }
    }

    var userIsLoggedIn: Bool {
        currentUser != nil
    }

    // ...
}
Run Code Online (Sandbox Code Playgroud)

如果我想使用Combine 创建一个反应式等效项,例如用于SwiftUI,我可以轻松添加@Published到存储的属性以生成Publishers,但不能用于计算属性。

    @Published var userIsLoggedIn: Bool { // Error: Property wrapper cannot be applied to a computed property
        currentUser != …
Run Code Online (Sandbox Code Playgroud)

ios swift reactive swiftui combine

55
推荐指数
3
解决办法
2万
查看次数

标签 统计

combine ×1

ios ×1

reactive ×1

swift ×1

swiftui ×1