In chapter 6, the authors propose a great solution to make LinkedList conform to the Collection protocol. This makes perfect sense to use a linked list with a familiar set of APIs.
I have a concern though regarding the subscript
method declaration, which can be found here:
public subscript(position: Index) -> Value {
position.node!.value
}
This seems problematic because the Index.node
has a type of Node<Value>?
. If the node value is nil
, then this force unwrapping will crash. Take this example:
let emptyList = LinkedList<Int>()
print(emptyList[0]) // crash, since no nodes exist yet
Should we just be extra careful when using linked list subscripts, and ensure that they aren’t empty before trying to subscript? This would mirror the behavior of array subscripting out of range, but seems like a non-optimal solution for users.