implement a linked list class in swift in swift

Here's an example implementation of a linked list class in Swift:

main.swift
class LinkedListNode<T> {
    var value: T
    var next: LinkedListNode?
    
    init(_ value: T) {
        self.value = value
    }
}

class LinkedList<T> {
    var head: LinkedListNode<T>?
    var tail: LinkedListNode<T>?
    
    var isEmpty: Bool {
        return head == nil
    }
    
    func append(_ value: T) {
        let newNode = LinkedListNode(value)
        
        if let tailNode = tail {
            tailNode.next = newNode
        } else {
            head = newNode
        }
        
        tail = newNode
    }
    
    func nodeAt(_ index: Int) -> LinkedListNode<T>? {
        if index >= 0 {
            var node = head
            var i = index
            while node != nil {
                if i == 0 { return node }
                i -= 1
                node = node!.next
            }
        }
        return nil
    }
    
    subscript(index: Int) -> T {
        let node = nodeAt(index)!
        return node.value
    }
}
959 chars
48 lines

This implementation consists of two classes: LinkedListNode and LinkedList. Each LinkedListNode object contains a value of a specific type and a reference to the next node in the linked list. The LinkedList class implements the linked list itself, with properties for the head and tail nodes, a function to append new nodes to the end of the list, a function to retrieve a node at a specific index, and a subscript to allow easy access to values in the list by index.

gistlibby LogSnag