如何将接收器结果分配给变量
How to assign sink result to variable
我想将通知中心发布者的结果分配给变量 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
this 作为列表
移动订阅单位
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>()
}
我想将通知中心发布者的结果分配给变量 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
this 作为列表
移动订阅单位
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>()
}