4

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

rmaddy
  • 314,917
  • 42
  • 532
  • 579
Jake Ortiz
  • 503
  • 9
  • 20
  • Related: [how to create generic protocols in swift iOS?](http://stackoverflow.com/questions/24469913/how-to-create-generic-protocols-in-swift-ios), [Swift Generic Protocol](http://stackoverflow.com/questions/25082769/swift-generic-protocol). – Martin R Jan 04 '15 at 17:20

1 Answers1

3

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

}
akashivskyy
  • 44,342
  • 16
  • 106
  • 116