Swift 合并错误:'Publisher' 上的方法需要 .Failure'(又名 'WeatherError')和 'Never' 是等价的

Pio*_*979 9 xcode ios swift combine

我现在正在学习 Swift Combine,找到了非常简单的视频教程,但是由于某种原因,当我尝试在 PassthroughSubject<Int, WeatherError>() 中使用我的枚举时出现错误

检查此代码:

import Combine 

enum WeatherError: Error {
   case thingsJustHappen
   
}
let weatherPublisher = PassthroughSubject<Int, WeatherError>()


let subscriber = weatherPublisher
   .filter {$0 > 10}
   .sink { value in
       print("\(value)")
   }

weatherPublisher.send(10)
weatherPublisher.send(30)
Run Code Online (Sandbox Code Playgroud)

“.filter”突出显示,错误是:

Referencing instance method 'sink(receiveValue:)' on 'Publisher' 
requires the types 'Publishers.Filter<PassthroughSubject<Int, WeatherError>>.Failure' 
(aka 'WeatherError') and 'Never' be equivalent
Run Code Online (Sandbox Code Playgroud)

令人惊讶的是,这段代码在视频教程中有效。我怎样才能让我的 WeatherError 和 Never 相等???

Cri*_*tik 16

您需要提供两个处理程序,完成一个和值一:

let subscriber = weatherPublisher
    .filter { $0 > 10 }
    .sink(receiveCompletion: { _ in }, receiveValue: { value in
       print("\(value)")
    })
Run Code Online (Sandbox Code Playgroud)

这是必需的,因为单参数sink, 仅适用于永远不会失败的发布者:

extension Publisher where Self.Failure == Never {
    /// ... many lines of documentation omitted
    public func sink(receiveValue: @escaping ((Self.Output) -> Void)) -> AnyCancellable
}
Run Code Online (Sandbox Code Playgroud)

  • @Piotr979,是的,过时的教程有时比没有教程更糟糕:) (2认同)