How is .enumerated() O(1) time?

Javid Poornasir
1 min readApr 29, 2022

--

#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:

https://github.com/apple/swift/blob/c35d508600516b892732e2fd3f0f0a17ca4562ba/stdlib/public/core/Algorithm.swift#L116

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:

--

--

Javid Poornasir
Javid Poornasir

Written by Javid Poornasir

I generally focus on iOS technologies

No responses yet