Directed graphs, as the name denotes, are graphs where the edges are directed to another node. Just because A points to B doesn’t mean that B points to A.

To implement directed graphs, we’ll need to add a parameter for bidirectional support instead of all edges being bidirectional by default.

Undirected graphs are a bit easier! They are graphs where the edges are not directed to one another. That is, A points to B and B points to A with the same edge.

To implement undirected graphs, we’ll use the parameterized bidirectional support used for directed graphs.

Let’s add bidirectional support to our graph.



Add a third parameter, isBidirectional of type Bool to the addEdge(from:to:) method. Give it a default value of true.


Add a line to the end of addEdge(from:to:isBidirectional) and create an if statement that checks if isBidirectional is true. If so, then:

  1. Append a new GraphEdge to edges that connects nodeTwo to nodeOne
  2. Call addNeighbor(_:) and add nodeOne as a neighbor to nodeTwo

Next, in the addEdges(from:to:) method, change the neighboringNodes from an array of GraphNode objects to an array of (GraphNode, Bool) tuples. Give the GraphNode a name of node and the Bool a name of isBidirectional. You should see a syntax error because the body of the function needs to be updated to use the new type.


Inside the for loop in the method, unpack the tuple into arguments node and isBirectional.


Finally, modify the call to addEdge(from:to:isBidirectional) for each node to include the argument isBidirectional.

Take this course for free

Mini Info Outline Icon
By signing up for Codecademy, you agree to Codecademy's Terms of Service & Privacy Policy.

Or sign up using:

Already have an account?