With GraphNode
complete, let’s implement the the GraphEdge
structure.
The GraphEdge
structure represents the connection between graph nodes. It will hold each conjoined node as a property.
Let’s create the GraphEdge
structure and define Graph
functions to add edges in the graph.
Instructions
Declare a new structure GraphEdge
. GraphEdge
will contain two constants, nodeOne
and nodeTwo
. These properties are the GraphNode
instances that will be connected in each edge. GraphEdge
will also have an initializer init(nodeOne: GraphNode, nodeTwo: GraphNode)
to allow for instantiation with assigned instance variables.
With GraphEdge
defined, let’s create a new edges
property inside Graph
. This new property will be an array of GraphEdge
. In the Graph
initializer, set edges
equal to an empty array.
With GraphEdge
defined, let’s define creating edges inside the Graph
class.
Create a new method addEdge(from:to:)
with parameter names nodeOne
and nodeTwo
that are GraphNode
instances.
Inside addEdge(from:to:)
, use the Array.append(_:)
method to add a new instance of GraphEdge
to the edges
property. Additionally, call the GraphNode.addNeighbor(_:)
function on nodeOne
with nodeTwo
as the argument.
We’ll also create another method addEdges(from:to:)
with parameters names nodeOne
and neighboringNodes
where nodeOne
is a GraphNode
and neighboringNodes
is an array of GraphNode
.
Inside addEdges(from:to:)
, create a for node in neighboringNodes
loop that iterates through each neighboring node. In the body of the loop, call addEdge(from:to:)
passing in nodeOne
and node
as parameters.