The Graph, GraphNode, and GraphEdge structures are almost complete! The last piece to the current Graph implementation is the ability to remove nodes.

Removing a node in a graph is a bit more complex as compared to removing one from a tree. We’ll need to:

  • Remove it from the nodes array
  • Remove any edges that contain the node from the edges array
  • Remove the node from any other nodes’s neighboringNodes array.



Get started by creating a new Graph method removeNode(_:) with an omitted argument label and an internal parameter node of type GraphNode.


Inside removeNode(_:), create an if let constant index equal to the first index inside nodes that matches the node to remove. If a node is found, remove the node from the nodes array using the Array.remove(at:) method.


After the if let statement, assign edges to edges filtered where GraphEdge.nodeOne or GraphEdge.nodeTwo is not equal to the node to remove.


As a final step, we’ll need to remove the node as a neighbor from each node in the nodes array. Use a forEach on nodes and call removeNeighbor(node) on each element using shorthand argument syntax.

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?