define graph in swift

In Swift, one way to define a graph is using an adjacency list. Here's an example implementation:

class Graph<T> {
    var adjacencyList: [T: [T]] = [:]
    func addEdge(_ fromNode: T, toNode: T) {
        if adjacencyList[fromNode] == nil {
            adjacencyList[fromNode] = []
256 chars
11 lines

In this implementation, the Graph class has a dictionary property called adjacencyList. The keys of this dictionary are the nodes of the graph, and the values are arrays of the nodes that the key node is connected to.

The addEdge method adds a new edge to the graph. The fromNode parameter is the node that the edge starts from, and the toNode parameter is the node that the edge ends at. If fromNode is not already in the adjacencyList, a new entry is added with an empty array as the value. Then, toNode is appended to the array value of the fromNode entry.

Here's an example of how to use this implementation to create a graph and add edges:

let graph = Graph<String>()
graph.addEdge("A", toNode: "B")
graph.addEdge("A", toNode: "C")
graph.addEdge("B", toNode: "D")
graph.addEdge("C", toNode: "E")
156 chars
6 lines

This code creates a graph with five nodes ("A", "B", "C", "D", and "E") and four edges. Node "A" is connected to nodes "B" and "C", node "B" is connected to node "D", and node "C" is connected to node "E".

gistlibby LogSnag