How to create a dependent common protocol in fast

I am trying to use protocols to give specific specifications to the structures that will implement them, but I need to be able to create these common ones.

For instance:

protocol NodeType {
}

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

The problem is that both nodes can be different types of structures that implement the implementation of the NodeType protocol

In an ideal world, I need the following:

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

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

Is something like this currently fast? thanks in advance

+4
source share
1 answer

. .

protocol NodeType {

}

protocol EdgeType {

    associatedtype Node: NodeType

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

}

EdgeType, NodeType:

struct MyNode: NodeType {

}

struct MyEdge: EdgeType {

    associatedtype Node = MyNode

    var fromNode: MyNode {
        return MyNode()
    }

    var toNode: MyNode {
        return MyNode()
    }

}
+3

Source: https://habr.com/ru/post/1569901/


All Articles