How do I implement a generic linked list in Swift?

Implementing a generic linked list in Swift allows for a flexible data structure that can hold any data type. Below is an example of how to create a simple generic linked list.

class Node { var value: T var next: Node? init(value: T) { self.value = value self.next = nil } } class LinkedList { private var head: Node? private var tail: Node? private var count: Int = 0 var isEmpty: Bool { return head == nil } var size: Int { return count } func append(value: T) { let newNode = Node(value: value) if let tailNode = tail { tailNode.next = newNode } else { head = newNode } tail = newNode count += 1 } func printList() { var currentNode = head while let node = currentNode { print(node.value, terminator: " -> ") currentNode = node.next } print("nil") } } let list = LinkedList() list.append(value: 1) list.append(value: 2) list.append(value: 3) list.printList() // Output: 1 -> 2 -> 3 -> nil

generic linked list swift data structure linked list implementation swift programming