如何在 Swift 中的 Combine 中的订阅者中引用 self



刚刚掌握 Combine 并遇到了一个问题,当它从Publisher接收值时,我需要在我的类中调用一个方法,在这种情况下是来自NotificationCenterNotification......

这是订阅...

let subscribe = NotificationCenter.default.publisher(for: Notification.Name(rawValue: "LocalTalkNotificationReceivedData"), object: nil)
.map( {
($0.object as! Data)
} )
.sink(receiveValue: {
self.interpretIncoming(data: $0)
})

编译器告诉我的是Use of unresolved identifier 'self'. 很晚了,我有点累了,有人有想法吗? Xcode 11 beta 5 on Catalina beta 5 顺便说一句...

完整文件:

import Foundation
import Combine
import SwiftUI
public class MessageData: ObservableObject, Identifiable {
public var peerData: [Peer] = [Peer]()
public var messageData: [Message] = [Message]()
public var objectWillChange = PassthroughSubject<Void, Never>()
let subscribe = NotificationCenter.default.publisher(for: Notification.Name(rawValue: "LocalTalkNotificationReceivedData"), object: nil)
.map( {
($0.object as! Data)
} )
.sink(receiveValue: {
self.interpretIncoming(data: $0)
})
init() {
self.setupDummyData()
}
private func setupDummyData() {
self.peerData = self.load("peerData.json")
self.messageData = self.load("messageData.json")
}
func addMessage(message: String, sender: MessageSource, name: String) {
let newMessage = Message(id: Date().hashValue,
content: message,
source: sender,
correspondent: name)
self.messageData.append(newMessage)
self.objectWillChange.send()
}
func load<T: Decodable>(_ filename: String, as type: T.Type = T.self) -> T {
let data: Data
guard let file = Bundle.main.url(forResource: filename, withExtension: nil)
else {
fatalError("Couldn't find (filename) in main bundle.")
}
do {
data = try Data(contentsOf: file)
} catch {
fatalError("Couldn't load (filename) from main bundle:n(error)")
}
do {
let decoder = JSONDecoder()
return try decoder.decode(T.self, from: data)
} catch {
fatalError("Couldn't parse (filename) as (T.self):n(error)")
}
}
func interpretIncoming(data sent: Data) {
do {
let receivedTransmission = try NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(sent) as! [String: Any]
self.addMessage(message: receivedTransmission["messagePayload"] as! String,
sender: .them,
name: receivedTransmission["messageSender"] as! String)
} catch {
print("FAILED DECODING THING")
}
}

}

你问题中的所有内容都是红鲱鱼,除了self这个词。你是说:

class MessageData: ObservableObject, Identifiable {
let subscribe = ... self ...
}

您不能在属性声明的初始值设定项中提及self,因为我们正在初始化self;目前还没有self

这里一个简单的解决方案可能是将let subscribe更改为lazy var subscribe,但是您必须在实际代码中询问subscribe的值才能进行初始化。但是,还有许多其他可能的方法。

Self 在您调用的上下文中不存在。许多解决此问题的方法包括将 interpretIncoming 定义为闭包变量或使其成为类方法并根据需要调用。

相关内容

  • 没有找到相关文章