Log in from a computer to take this course

You'll need to log in from a computer to start Introduction to Non-linear Data Structures in Swift. But you can practice or keep up your coding streak with the Codecademy Go app. Download the app to get started.

apple storegoogle store
Learn

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

1.

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.

2.

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.

3.

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.

4.

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.

5.

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.

6.

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.

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?