The key is indeed that removeFirst()
is mutating, while first
is nonâmutating.
- â Both can return the value if it is there.
- â Both could (theoretically) return
nil
when the collection is empty.
At this point, first
is able to fulfill everything it purports to do. Hence it returns Element?
. On the other hand, removeFirst()
purports to do more:
- â
removeFirst()
can perform the removalâmutating the collectionâif it has a first element.
- â
removeFirst()
is unable to perform the removal if there is nothing to remove. It cannot access the first index to trigger any expected side effects. There is no action it could take that would result in the expected decrementation of count
. In short, it cannot satisfy what you asked it to do.
Hence, if the collection is empty, removeFirst()
traps, indicating that the removal failed. (And since the nil
returning situation would only ever follow the trap, the hypothetical nil
return would be unreachable. Ergo there is no reason for the return value to be optional at all, and removeFirst()
returns a nonâoptional Element
.)