In this lesson, we’ll define the necessary structures to implement the Graph data structure in Swift. Similar to the Trees lesson, we’ll define the base class Graph and a GraphNode structure to contain the data for each node in the graph. Additionally, we’ll need to define a structure to connect the nodes within the graph. This is important because graphs are not bounded by the parent-children relationship.

As we build out these structures and classes, we’ll need to ensure that our Graph implementation is flexible enough to support a variety of graphs. Our implementation will focus on supporting acyclic, cyclic, undirected, and weighted graphs.

With this in mind, let’s change the GraphNode structure to account for the Graph data structure. The initial code provided is a starting point with the Tree implementation from an earlier lesson.



The Graph data structure will use edges to connect GraphNode instances. Unlike Trees, the Graph class will contain the relationships within the graph. GraphNode only needs to know its neighbors. Due to the aforementioned, only one addNeighbor(_:) method is needed. Remove the extra addNeighbor methods: addNeighbor(newNeighborData: String) addNeighbor(_ newNeighbor: [GraphNode])


Since nodes are not restricted to only having children nodes, removing a neighbor works differently then the Trees data structure. Let’s account for this in the GraphNode.removeNeighbor(_:) method. First, remove the code inside the removeNeighbor(_:) method.


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

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?