如何将接收器结果分配给变量

问题描述 投票:0回答:1

我想将通知中心发布者的结果分配给变量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用作列表

swift swiftui nsnotificationcenter combine
1个回答
1
投票

在初始状态下移动订阅

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>()
}
© www.soinside.com 2019 - 2024. All rights reserved.