Opaque types with some keyword in Swift - Time & Space Complexity
We want to understand how the time it takes to run code using opaque types with the some keyword changes as input grows.
Specifically, how does using some affect the speed of functions that return values?
Analyze the time complexity of the following Swift code using some keyword.
func makeNumbers() -> some Sequence {
return 1...1000
}
for number in makeNumbers() {
print(number)
}
This code returns a sequence of numbers using an opaque type and then loops through it to print each number.
Look for loops or repeated steps that take time.
- Primary operation: Looping through each number in the sequence.
- How many times: Exactly 1000 times, once for each number.
As the number of items in the sequence grows, the loop runs more times.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 loops |
| 100 | 100 loops |
| 1000 | 1000 loops |
Pattern observation: The work grows directly with the number of items; double the items, double the work.
Time Complexity: O(n)
This means the time to run grows in a straight line with the number of elements we process.
[X] Wrong: "Using some keyword makes the function run faster or slower by itself."
[OK] Correct: The some keyword only hides the exact type but does not change how many times the code runs. The loop still runs once per item.
Understanding how opaque types affect performance helps you explain your code choices clearly and shows you know how Swift handles types under the hood.
What if the sequence returned by the function was infinite? How would that affect the time complexity when looping?