How is .enumerated() O(1) time?
#Swift5
I’ve seen confusion online pertaining to how and why .enumerated() is an O(1) time complexity operation instead of O(N) since you still need to traverse through every item. Let’s quickly clear that up.
The .enumerated( ) method creates the enumerator, and the creation of that enumerator only takes O(1) time — Refer to Line 134 below for an example of exactly what that means and then we’ll dig in:
Creating “s” in L134 highlighted above is the O(1) time operation. You can then loop through “s” (as shown below in L135 to L137); the looping is still O(N) time.
Most Apple/Xcode docs don’t separate the creation of the enumerator from its use w/ the for-in loop, which likely caused you confusion if you’ve never seen an enumerator being initialized in a manner shown as is shown above.
Remember: .enumerated( ) is a function.
— — — — — — — — — — — — — — —
REFERENCES: