我想将通知中心发布服务器的结果分配给变量alert。我得到的错误是:

Cannot use instance member 'alerts' within property initializer; property initializers run before 'self' is available

有人能帮我吗?
import Foundation
import SwiftUI
import Combine

final class PublicAlerts: ObservableObject{

    init () {
        fetchAlerts()
    }

    var alerts = [String](){
        didSet {
            didChange.send(self)
        }
    }

    private func fetchPublicAssets(){
        backEndService().fetchAlerts()
    }

    let publicAssetsPublisher = NotificationCenter.default.publisher(for: .kPublicAlertsNotification)
        .map { notification in
            return notification.userInfo?["alerts"] as! Array<String>
        }.sink {result in
            alerts = result
        }

    let didChange = PassthroughSubject<PublicAlerts, Never>()
}

稍后我将在SwiftUI中使用alerts作为列表

最佳答案

在init中移动订阅

final class PublicAlerts: ObservableObject{

    var anyCancelable: AnyCancellable? = nil

    init () {
        anyCancelable = NotificationCenter.default.publisher(for: .kPublicAlertsNotification)
            .map { notification in
                return notification.userInfo?["alerts"] as! Array<String>
        }.sink {result in
            alerts = result
        }
        fetchAlerts()
    }

    var alerts = [String](){
        didSet {
            didChange.send(self)
        }
    }

    private func fetchPublicAssets(){
        backEndService().fetchAlerts()
    }

    let didChange = PassthroughSubject<PublicAlerts, Never>()
}

关于swift - 如何将接收器结果分配给变量,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/58448055/

10-13 04:03