How do I implement a generic graph in Swift?

Implementing a generic graph in Swift involves creating a class or struct that can handle nodes and edges in a flexible manner, allowing you to work with any type of data. Below is a basic implementation of a generic graph in Swift.

        public class Graph {
            private var adjacencyList: [T: [T]] = [:]

            public func addVertex(_ vertex: T) {
                adjacencyList[vertex] = []
            }

            public func addEdge(from source: T, to destination: T) {
                adjacencyList[source]?.append(destination)
                adjacencyList[destination]?.append(source) // For undirected graph
            }

            public func getEdges(from vertex: T) -> [T]? {
                return adjacencyList[vertex]
            }

            public func vertices() -> [T] {
                return Array(adjacencyList.keys)
            }
        }

        // Example of using the generic graph
        let graph = Graph()
        graph.addVertex("A")
        graph.addVertex("B")
        graph.addEdge(from: "A", to: "B")
        print(graph.getEdges(from: "A")) // Output: ["B"]
        

Generic Graph Swift Graph Implementation Swift Programming