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?
Practice
buildOptional in Swift's result builders?Solution
Step 1: Understand buildOptional's role
buildOptionalis designed to handle optional code blocks, allowing them to be included if present or skipped if nil.Step 2: Compare with other builder functions
buildEitherchooses between two paths, butbuildOptionalspecifically wraps optional code, making it flexible for optional UI parts.Final Answer:
To wrap optional code blocks so they can be included or skipped -> Option BQuick Check:
buildOptional wraps optionals = B [OK]
- Confusing buildOptional with buildEither
- Thinking buildOptional forces unwrapping
- Assuming buildOptional creates loops
buildEither for choosing the first branch in a Swift result builder?Solution
Step 1: Recall buildEither syntax
The correct syntax uses named parametersfirstorsecondto specify the branch.Step 2: Identify the correct usage
buildEither(first: { Text("First") }) usesbuildEither(first: { ... }), which matches the official Swift syntax for choosing the first branch.Final Answer:
buildEither(first: { Text("First") }) -> Option CQuick Check:
buildEither first branch = A [OK]
- Using incorrect parameter names like option or branch
- Confusing first and second parameters
- Trying to pass branch as enum instead of named argument
enum ResultBuilder {
static func buildEither(first: String) -> String { "First: \(first)" }
static func buildEither(second: String) -> String { "Second: \(second)" }
}
let result = ResultBuilder.buildEither(first: "Hello")
print(result)Solution
Step 1: Identify which buildEither is called
The code callsbuildEither(first: "Hello"), so the first overload is used.Step 2: Understand the returned string
The first overload returns the string "First: Hello" which is printed.Final Answer:
First: Hello -> Option DQuick Check:
buildEither first branch returns "First: Hello" = A [OK]
- Assuming second branch runs when first is called
- Expecting just the input string without prefix
- Thinking this causes a compile error
struct Builder {
@resultBuilder
struct MyBuilder {
static func buildEither(first: String) -> String { first }
static func buildEither(second: String) -> String { second }
}
}
let value = Builder.MyBuilder.buildEither(third: "Oops")Solution
Step 1: Identify the method call
The code callsbuildEither(third: "Oops"), but onlyfirstandsecondparameters exist.Step 2: Understand the fix
To fix, replacethirdwith eitherfirstorsecondto match the defined overloads.Final Answer:
Error: No 'third' parameter; fix by using 'first' or 'second' -> Option AQuick Check:
buildEither only accepts first or second = C [OK]
- Trying to add unsupported parameter names
- Ignoring static keyword requirements
- Assuming code runs without error
buildOptional and buildEither together to conditionally build a SwiftUI view that shows "Logged In" if a user is logged in, "Guest" if not logged in but guest mode is enabled, and nothing otherwise?Solution
Step 1: Understand the conditions
We have three cases: logged in, guest mode, and neither.buildEithercan choose between logged in and guest mode views.Step 2: Use buildOptional for the third case
The third case (neither) means no view, so wrap the guest mode view inbuildOptionalto include it only if guest mode is enabled.Step 3: Combine both builders
UsebuildEitherto select logged in or guest mode, andbuildOptionalto skip guest mode if disabled, resulting in no view if neither condition is true.Final Answer:
Use buildOptional to wrap guest mode view, and buildEither to choose between logged in and guest -> Option AQuick Check:
buildOptional wraps optional guest, buildEither picks logged in or guest = D [OK]
- Using buildEither alone for optional skipping
- Using buildOptional alone for branching
- Not handling the 'no view' case properly
Ready to prove it?
Pass the test and this pattern moves unknown
