“Protocol ...只能用作通用约束,因为它具有Self或相关类型要求”意思? [英] What does "Protocol ... can only be used as a generic constraint because it has Self or associated type requirements" mean?

查看:923
本文介绍了“Protocol ...只能用作通用约束,因为它具有Self或相关类型要求”意思?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个字典(实际上是一个 HashSet ),并将其键入一个自定义协议在Swift中,但它给了我标题中的错误:

lockquote
协议'myProtocol'只能用作通用约束,因为它有自我或相关类型的要求


我无法正面或反面。

  protocol观察:Hashable {} 

var observers = HashSet< Observing>()






更新:



为什么这是查看此视频的方式。


$ b $协议观察从协议继承 Hashable ,它继而从协议<继承code> Equatable 。 Protocol Equatable 具有以下要求:

  func ==(lhs: Self,rhs:Self) - > Bool 

一个包含 Self 某处的协议里面它不能在任何地方使用,除非在类型约束中。



这里是一个类似的问题。


I am trying to create a Dictionary (actually a HashSet) keyed on a custom protocol in Swift, but it is giving me the error in the title:

Protocol 'myProtocol' can only be used as a generic constraint because it has Self or associated type requirements

and I can't make heads nor tails of it.

protocol Observing: Hashable { }

var observers = HashSet<Observing>()


Update:

For the best possible explanation for why this is the way it is check out this video.


解决方案

Protocol Observing inherits from protocol Hashable, which in turn inherits from protocol Equatable. Protocol Equatable has the following requirement:

func ==(lhs: Self, rhs: Self) -> Bool

And a protocol that contains Self somewhere inside it cannot be used anywhere except in a type constraint.

Here is a similar question.

这篇关于“Protocol ...只能用作通用约束,因为它具有Self或相关类型要求”意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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