zalogatomek
zalogatomek

Reputation: 746

Swift protocol property of type Set<Self>

I'm trying to create simple protocol:

protocol Groupable
{
    var parent: Self? { get }
    var children: Set<Self> { get }
}

But children property doesn't compile, because: Type 'Self' does not conform to protocol 'Hashable'.

Is there any to way to ensure Self to be Hashable? Or any other workaround for this, for example by using associatedtype?

Upvotes: 0

Views: 548

Answers (2)

HHK
HHK

Reputation: 1487

You need to use protocol inheritance:

A protocol can inherit one or more other protocols and can add further requirements on top of the requirements it inherits. The syntax for protocol inheritance is similar to the syntax for class inheritance, but with the option to list multiple inherited protocols, separated by commas.

By inheriting from Hashable, your class will need to conform to this protocol. Also, in your specific example, you'll need to make your class final. For an explanation, see A Swift protocol requirement that can only be satisfied by using a final class

Here is an example:

protocol Groupable: Hashable {
  var parent: Self? { get }
  var children: Set<Self> { get }
}


final class MyGroup: Groupable {

  var parent: MyGroup?
  var children = Set<MyGroup>()

  init() {

  }

  var hashValue: Int {
      return 0
  }
}

func ==(lhs: MyGroup, rhs: MyGroup) -> Bool {
  return true
}



let a = MyGroup()

Upvotes: 1

arithma
arithma

Reputation: 436

The way to put constraints in protocols is similar to how you specify protocol conformance (they're the same thing after all)

protocol Groupable: Hashable
{
    var parent: Self? { get }
    var children: Set<Self> { get }
}

Upvotes: 1

Related Questions