What does “Protocol … can only be used as a generic constraint because it has Self or associated type requirements” mean?

≡放荡痞女 提交于 2019-11-26 06:00:32

问题


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>()

回答1:


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.




回答2:


To solve this you could use generics. Consider this example:

class GenericClass<T: Observing> {
   var observers = HashSet<T>()
}


来源:https://stackoverflow.com/questions/24926310/what-does-protocol-can-only-be-used-as-a-generic-constraint-because-it-has

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!