"some Protocol" 导致类型不符合协议
"some Protocol" causes type to not conform to protocol
我不明白为什么这不能编译。如果我从 P
类型中删除 where
限制,它就会执行。
import Combine
protocol Foo {
associatedtype P: Publisher where P.Output == Int
var publisher: P { get }
}
struct Bar: Foo {
var publisher: some Publisher {
Just(1)
}
}
错误说 Type 'Bar' does not conform to protocol 'Foo'
。我想这是因为 publisher
return 类型不仅仅是任何 some Publisher
。但在 SwiftUI 中,View
使用类似的方法,只是它对 View
类型没有限制。
有什么方法可以编译这段代码吗?
编译不通过的原因是因为some Publisher
声明了一个不透明的类型,但是协议要求类型必须是“see-through”。
some Publisher
是“不透明的”,因为调用者无法确切地看到 属性 实际是什么类型,只能知道它符合 Publisher
。这与 P.Output
必须是 Int
的协议要求直接矛盾。 要检查P.Output
是Int
,你必须“看穿”some Publisher
,但你不能。
由于编译器无法检查发布者的 Output
,它无法检查您的类型是否真的符合协议。因此它选择“安全路线”得出结论,你的类型不符合协议。
我认为你应该使用 AnyPublisher
类型的橡皮擦:
var publisher: AnyPublisher<Int, Never> {
Just(1).eraseToAnyPublisher()
}
SwiftUI 的View
协议不存在这个问题,因为它不需要Body
为“see-through”。它只需要 Body
是 View
的构象,根据定义,some View
是
我不明白为什么这不能编译。如果我从 P
类型中删除 where
限制,它就会执行。
import Combine
protocol Foo {
associatedtype P: Publisher where P.Output == Int
var publisher: P { get }
}
struct Bar: Foo {
var publisher: some Publisher {
Just(1)
}
}
错误说 Type 'Bar' does not conform to protocol 'Foo'
。我想这是因为 publisher
return 类型不仅仅是任何 some Publisher
。但在 SwiftUI 中,View
使用类似的方法,只是它对 View
类型没有限制。
有什么方法可以编译这段代码吗?
编译不通过的原因是因为some Publisher
声明了一个不透明的类型,但是协议要求类型必须是“see-through”。
some Publisher
是“不透明的”,因为调用者无法确切地看到 属性 实际是什么类型,只能知道它符合 Publisher
。这与 P.Output
必须是 Int
的协议要求直接矛盾。 要检查P.Output
是Int
,你必须“看穿”some Publisher
,但你不能。
由于编译器无法检查发布者的 Output
,它无法检查您的类型是否真的符合协议。因此它选择“安全路线”得出结论,你的类型不符合协议。
我认为你应该使用 AnyPublisher
类型的橡皮擦:
var publisher: AnyPublisher<Int, Never> {
Just(1).eraseToAnyPublisher()
}
SwiftUI 的View
协议不存在这个问题,因为它不需要Body
为“see-through”。它只需要 Body
是 View
的构象,根据定义,some View
是