BuildOptional and buildEither in Swift - Time & Space Complexity
When using BuildOptional and buildEither in Swift, it's important to understand how the code execution time changes as input grows.
We want to see how these builders affect the number of steps the program takes.
Analyze the time complexity of the following Swift code using BuildOptional and buildEither.
func process(values: [Int]?) {
if let values = values {
for value in values {
print(value)
}
} else {
print("No values")
}
}
func choose(value: Int) {
switch value {
case 1: print("One")
case 2: print("Two")
default: print("Other")
}
}
This code uses optional handling and conditional branches similar to BuildOptional and buildEither to decide what to run.
Look for loops or repeated steps in the code.
- Primary operation: The for-loop that prints each value in the array.
- How many times: Once for each item in the input array if it exists.
The number of print operations grows as the number of values grows.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 prints |
| 100 | 100 prints |
| 1000 | 1000 prints |
Pattern observation: The work grows directly with the number of items.
Time Complexity: O(n)
This means the time to run grows in a straight line with the number of input items.
[X] Wrong: "Using BuildOptional or buildEither makes the code run instantly regardless of input size."
[OK] Correct: These builders only control which code runs, but if that code loops over many items, the time still grows with input size.
Understanding how optional and conditional code affects time helps you explain your code's efficiency clearly and confidently.
What if the input array was replaced with a nested array? How would that change the time complexity?