I have read through the book entirely with out doing any of the coding examples and now I am re-reading the content with doing the examples.
Upon reaching the LinkedList
section we can view the insert function:
@discardableResult
public mutating func insert(_ value: Value, after node: Node<Value>) -> Node<Value> {
guard tail !== node else {
append(value)
return tail!
}
node.next = Node(value: value, next: node.next)
return node.next!
}”
There are a few questions that come up when reviewing this code that are more apparent when writing it out.
-
What if the node does not exists in the LinkedList?
i. Generally these are developer errors so can be overlooked, but in some scenarios we would cause a fatalerror. I understand that causing a fatalError would be O(n) of work and thus can ruin the efficiency of a LinkedList. Is that why we don’t opt in to guard out early? -
I am misunderstanding the relevance of the condition
tail !== node
. In the event that the tail is identical (not equal) to the current node wouldn’t our code be sufficient enough to handle this case? (code below)
i. The benefit of callingappend
would also check ifhead != nil
, but if our head is equal to nil then our linked list is empty and therefore the node does not exists in our linked list. Moving back up to theinsert
call, thetail !== node
would evaluate tonil !== node
which is true so we would continue to attach our node to the stray node.
node.next = Node(value: value, next: node.next)
return node.next!
My question comes down to, is there some point I am missing or do we not need to add that additional test?