Jake Ortiz
Jake Ortiz

Reputation: 513

How create dependent generic protocol in swift

I'm trying to using protocols to give certain specifications to structs that will implement them, but I need to be able to make these generic.

For example:

protocol NodeType {
}

protocol EdgeType {
  var fromNode: NodeType
  var toNode: NodeType
}

The problem is that both node could be different structs type that implement that implement the protocol NodeType

In a perfect world I would need this:

protocol EdgeType<T: NodeType> {
  var fromNode: T
  var toNode: T
}

to make sure that both nodes are the same class or struct type

Is something like this possible currently in swift? Thanks in advance

Upvotes: 4

Views: 371

Answers (1)

akashivskyy
akashivskyy

Reputation: 45180

You should take a look at Associated Types. They're kind of generics for protocols.

protocol NodeType {

}

protocol EdgeType {

    associatedtype Node: NodeType

    var fromNode: Node { get }
    var toNode: Node { get }

}

Then you can conform to EdgeType by specifying the concrete NodeType implementation:

struct MyNode: NodeType {

}

struct MyEdge: EdgeType {

    associatedtype Node = MyNode

    var fromNode: MyNode {
        return MyNode()
    }

    var toNode: MyNode {
        return MyNode()
    }

}

Upvotes: 3

Related Questions