使用发布服务器协议



我想隐藏我的发布者实现:

public protocol MyPublisher: Combine.Publisher where Failure == Never, Output == MyType {
...
}
internal struct MyPublisherImpl: MyPublisher {
public typealias Output = MyType
public typealias Failure = Never
private let wrappedPublisher: SomeKnownPublisher
public func receive<S>(subscriber: S) where S : Subscriber, Never == S.Failure, Output == S.Input {
wrappedPublisher
.map{ <convert to MyType> }
.subscribe(subscriber)
}
...
}
public func makeMyPublisher(...) -> any MyPublisher { 
return MyPublisherImpl(...)
}
let myPublisher = makeMyPublisher(...)
myPublisher
.assign(to:.keyPath, on: someObject)
.store(in: &cancellables)

它工作得很好,直到我需要在我的出版商上使用任何功能:

let anotherMyPublisher = makeMyPublisher(...)
anotherMyPublisher
.map{...}
.assign(to:.anotherKeyPath, on: anotherObject)
.store(in: &cancellables)

在这种情况下,我有一个错误:

成员"map"不能用于"any MyPublisher"类型的值;考虑使用通用约束代替

当我从协议中删除"where"时,我会收到关于".assign(to:on:)"的相同错误。

我必须做些什么才能像其他常见的发布者一样使用MyPublisher?

您面临的根本问题是类型为any MyPublisher的变量不是MyPublisherany MyPublisher是一个存在论。

你说的是";至少存在一种实现CCD_ 4接口的类型。我希望你为我创建一个可以容纳任何此类值的框";。(您声明至少有一个实现抽象MyPubisher接口的具体类型"存在",因此术语为"存在")。

any MyPublisher类型的变量是一个可以容纳实现MyPubisher的任何类型的框,但这一点至关重要,框本身不实现MyPublisher's接口

这是一个装有MyPublisher的盒子,但它本身不是MyPublisher,所以它上面没有map这样的功能

您可能希望makeMyPubisher返回some MyPublisher。也就是说,返回一个符合MyPublisher的特定类型的实体,而不是一个可以包含实现MyPubisher的任何类型的东西的框。

最新更新