“某些协议"导致类型不符合协议 [英] "some Protocol" causes type to not conform to protocol

查看:57
本文介绍了“某些协议"导致类型不符合协议的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不明白为什么它不能编译.如果我从 P 类型中删除了 where 限制,它就会生效.

I don't understand why this doesn't compile. It does if I remove the where restriction from the P type.

import Combine

protocol Foo {
    associatedtype P: Publisher where P.Output == Int
    var publisher: P { get }
}

struct Bar: Foo {
    var publisher: some Publisher {
        Just(1)
    }
}

该错误表明类型'Bar'不符合协议'Foo'.我猜这是因为 publisher 返回类型不只是任何 some Publisher .但是在SwiftUI中, View 使用了类似的方法,只是它对 View 类型没有限制.

The error says that Type 'Bar' does not conform to protocol 'Foo'. I guess it's because publisher return type is not just any some Publisher. But in SwiftUI, the View uses a similar approach, just that it doesn't have restrictions over the View type.

有什么办法可以使这段代码编译?

Is there any way I can make this code to compile?

推荐答案

之所以无法编译,是因为 some Publisher 声明了不透明类型,但协议要求该类型必须为透明".

The reason why it doesn't compile is because some Publisher declares an opaque type, but the protocol requires that the type must be "see-through".

某些发布者是不透明的",从某种意义上讲,调用者无法确切看到属性的实际类型,只能知道它符合 Publisher .这与 P.Output 必须为 Int 的协议要求直接矛盾.要检查 P.Output 是否为 Int ,您必须查看"某些发布商 ,但不能.

some Publisher is "opaque" in the sense that callers cannot see exactly what type the property actually is, and can only know that it conforms to Publisher. This directly contradicts with the protocol requirement that P.Output has to be Int. To check P.Output is Int, you have to "see through" some Publisher, but you can't.

由于编译器无法检查发布者的 Output ,因此无法检查您的类型是否确实符合协议.因此,它选择安全路线"来选择安全路线".结论是您的类型不符合协议.

Since the compiler can't check the publisher's Output, it can't check whether your type really conforms to the protocol or not. Therefore it chooses the "safe route" concludes that your type does not conform to the protocol.

我认为您应该使用 AnyPublisher 类型的橡皮擦:

I think you should use the AnyPublisher type eraser:

var publisher: AnyPublisher<Int, Never> {
    Just(1).eraseToAnyPublisher()
}


SwiftUI的 View 协议不存在此问题,因为它不需要 Body 是透明的".它只需要 Body View 的遵循者,就定义而言,某些View


SwiftUI's View protocol does not have this problem because it does not require Body to be "see-through". It just requires that Body is a conformer of View, which some View, by definition, is.

这篇关于“某些协议"导致类型不符合协议的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆