解码数据?来自另一个出版商



我正在尝试解码另一个文件中的Publisher,该文件是dataService。$data,它是:

@Published var data: Data? = nil

在我使用网络管理器之前,它返回AnyPublisher<Data,>

let dataDownload = NetworkingManager.download(url: url)
casaSubscription = dataService.$data
.decode(type: [House].self, decoder: XMLDecoder())
.sink(receiveCompletion: NetworkingManager.handleCompletion, receiveValue: { [weak self] (returnedCasas) in
self?.house = returnedCasas
self?.houseSubscription?.cancel()
})

代替dataService。$data我有datdownload,它都工作得很好,但现在,我尝试使用dataService。$data,然后在

下面抛出错误Instance method 'decode(type:decoder:)' requires the types 'Published<Data?>.Publisher.Output' (aka 'Optional<Data>') and 'Data' be equivalent

Optional(Data)Data不是同一类型

在Combine中尽量避免可选。

一个简单的解决方案是声明一个空的Data实例
@Published var data = Data()

并在管道中过滤

casaSubscription = dataService.$data
.filter{!$0.isEmpty}
.decode(type: [House].self, decoder: XMLDecoder()) ...

或者-如果你真的想保留可选的

casaSubscription = dataService.$data
.compactMap{$0}
.decode(type: [House].self, decoder: XMLDecoder()) ...

最新更新