Home > OS >  swift : unexpected traverse print for custom linked list
swift : unexpected traverse print for custom linked list

Time:03-15

Here is a simple code I have to play with custom List in Swift

public class Node<Value> {
    public var value: Value
    public var next: Node?
    
    public init(value: Value, next: Node? = nil) {
        self.value = value
        self.next = next
    }
}

extension Node: CustomStringConvertible {
    public var description: String {
        guard let next = next else {
            return "\(value)"
        }
        
        return "\(value) -> "   String(describing: next)   " "
    }
}

func creating_and_linking_nodes()
{
    let node1 = Node(value: 1)
    let node2 = Node(value: 2)
    let node3 = Node(value: 3)
    
    node1.next = node2
    node2.next = node3
    
    print(node1)
}

I see the following output "1 -> 2 -> 3" which is a bit unexpected for me. Why is the list being traversed by print ? Is it a default behavior ? Is there a way to override it and print only 1 node ?

CodePudding user response:

    public var description: String {
        guard let next = next else {
            return "\(value)"
        }
        
        return "\(value) -> "   String(describing: next)   " "
    }
} 

Your code is written in such way that it traverse the list. So change it accordingly. This is a basic error.

  • Related