快速组合错误:'Publisher'上的方法需要 .失败"(又名"天气错误")和"从不"等效



我现在正在学习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)

&";。过滤器";突出显示,错误为:

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

令人惊讶的是,这段代码在视频教程中有效。如何使我的WeatherError和Never等价???

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

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

这是必要的,因为只有永远不会失败的发布者才能使用单个参数sink

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

如果将类型更改为Never:,它将起作用

let weatherPublisher = PassthroughSubject<Int, Never>()

或者创建一个新的Published变量:

@Published var weather = 0
let weatherPublisher = PassthroughSubject<Int, WeatherError>()
let weatherSubscriber = weather
.filter { $0 > 10 }
.sink { print($0) }
let subscriber = weatherPublisher
.sink { [weak self] value in
self?.weather = value
}

在Xcode 13&iOS 15.4此代码需要括号才能编译。

extension Publisher where Self.Failure ==  Never {
// because the publisher can NEVER FAIL - by design!
public  func sink(receiveValue: @escaping ((Self.Output) -> Void)) -> AnyCancellable {  }
}

相关内容

最新更新