Bird
Raised Fist0
Swiftprogramming~10 mins

BuildOptional and buildEither in Swift - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - BuildOptional and buildEither
Start
↓
Check Optional Value
Yes|No↓
buildOptional(value)
↓
Check Condition for Either
↓
buildEither(first:)
↓
Result Built
This flow shows how buildOptional handles optional values by including or skipping content, and buildEither chooses between two branches based on a condition.
Execution Sample
Swift
func test() {
  let opt: Int? = 5
  let result = buildOptional(opt) {
    "Value is \(opt!)"
  }
  let either = buildEither(first: "First")
  print(result ?? "No value", either)
}
This code uses buildOptional to include a string if the optional has a value, and buildEither to select the first branch.
Execution Table
StepActionInputResultNotes
1Check optional 'opt'opt = 5Has valueOptional is not nil
2Call buildOptional with value5"Value is 5"Includes content inside optional
3Call buildEither with first branchfirst: "First""First"Selects first branch
4Print resultsresult = "Value is 5", either = "First"Output: Value is 5 FirstPrints both results
5Change opt to nilopt = nilNo valueOptional is nil, buildOptional returns nil
6Call buildOptional with nilnilnilNo content included
7Call buildEither with second branchsecond: "Second""Second"Selects second branch
8Print resultsresult = nil, either = "Second"Output: No value SecondPrints fallback and second branch
💡 Execution stops after printing results for both optional present and nil cases.
Variable Tracker
VariableStartAfter Step 1After Step 5Final
opt55nilnil
resultnil"Value is 5"nilnil
eithernil"First""Second""Second"
Key Moments - 2 Insights
Why does buildOptional return nil when the optional is nil?
Because buildOptional only includes content if the optional has a value, as shown in execution_table row 6 where input is nil and result is nil.
How does buildEither decide which branch to take?
buildEither chooses the first or second branch explicitly, as shown in rows 3 and 7 where first or second branch is selected.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table at step 2, what is the result of buildOptional when opt = 5?
Anil
B"No value"
C"Value is 5"
D"First"
💡 Hint
Check the 'Result' column in execution_table row 2 for buildOptional with value.
At which step does buildOptional return nil because the optional is nil?
AStep 2
BStep 6
CStep 3
DStep 7
💡 Hint
Look at execution_table row 6 where input is nil and result is nil.
If we change buildEither to select the second branch at step 3, what would be printed?
A"Value is 5 Second"
B"Value is 5 First"
C"No value First"
D"No value Second"
💡 Hint
Refer to variable_tracker 'either' value changes and execution_table rows 3 and 7.
Concept Snapshot
buildOptional(value) includes content only if value is not nil.
buildEither(first:) or buildEither(second:) chooses one branch explicitly.
Use buildOptional to handle optional content.
Use buildEither to select between two alternatives.
If optional is nil, buildOptional returns nil.
buildEither does not depend on optional, chooses branch directly.
Full Transcript
This visual execution shows how Swift's buildOptional and buildEither work. buildOptional checks if an optional value exists. If it does, it includes the content; if not, it returns nil. buildEither chooses between two branches, first or second, explicitly. The execution table traces steps with optional present and nil cases, showing how results change. Variable tracking shows how opt, result, and either change over time. Key moments clarify why buildOptional returns nil when optional is nil and how buildEither selects branches. The quiz tests understanding of these steps and outcomes.

Practice

(1/5)
1. What is the main purpose of buildOptional in Swift's result builders?
easy
A. To choose between two code paths explicitly
B. To wrap optional code blocks so they can be included or skipped
C. To force unwrap optionals in code blocks
D. To create loops inside result builders

Solution

  1. Step 1: Understand buildOptional's role

    buildOptional is designed to handle optional code blocks, allowing them to be included if present or skipped if nil.
  2. Step 2: Compare with other builder functions

    buildEither chooses between two paths, but buildOptional specifically wraps optional code, making it flexible for optional UI parts.
  3. Final Answer:

    To wrap optional code blocks so they can be included or skipped -> Option B
  4. Quick Check:

    buildOptional wraps optionals = B [OK]
Hint: Remember: buildOptional handles optionals, buildEither picks sides [OK]
Common Mistakes:
  • Confusing buildOptional with buildEither
  • Thinking buildOptional forces unwrapping
  • Assuming buildOptional creates loops
2. Which of the following is the correct syntax to use buildEither for choosing the first branch in a Swift result builder?
easy
A. buildEither(option: 1) { Text("First") }
B. buildEither(second: { Text("First") })
C. buildEither(first: { Text("First") })
D. buildEither(branch: .first, content: { Text("First") })

Solution

  1. Step 1: Recall buildEither syntax

    The correct syntax uses named parameters first or second to specify the branch.
  2. Step 2: Identify the correct usage

    buildEither(first: { Text("First") }) uses buildEither(first: { ... }), which matches the official Swift syntax for choosing the first branch.
  3. Final Answer:

    buildEither(first: { Text("First") }) -> Option C
  4. Quick Check:

    buildEither first branch = A [OK]
Hint: Use named parameters first or second with buildEither [OK]
Common Mistakes:
  • Using incorrect parameter names like option or branch
  • Confusing first and second parameters
  • Trying to pass branch as enum instead of named argument
3. What will be the output of this Swift code using buildEither?
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)
medium
A. Compilation error
B. Second: Hello
C. Hello
D. First: Hello

Solution

  1. Step 1: Identify which buildEither is called

    The code calls buildEither(first: "Hello"), so the first overload is used.
  2. Step 2: Understand the returned string

    The first overload returns the string "First: Hello" which is printed.
  3. Final Answer:

    First: Hello -> Option D
  4. Quick Check:

    buildEither first branch returns "First: Hello" = A [OK]
Hint: Check which named parameter is used: first or second [OK]
Common Mistakes:
  • Assuming second branch runs when first is called
  • Expecting just the input string without prefix
  • Thinking this causes a compile error
4. Given this Swift code snippet, what is the error and how to fix it?
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")
medium
A. Error: No 'third' parameter; fix by using 'first' or 'second'
B. Error: Missing return statement; fix by adding return
C. Error: buildEither cannot be static; remove static keyword
D. No error; code runs fine

Solution

  1. Step 1: Identify the method call

    The code calls buildEither(third: "Oops"), but only first and second parameters exist.
  2. Step 2: Understand the fix

    To fix, replace third with either first or second to match the defined overloads.
  3. Final Answer:

    Error: No 'third' parameter; fix by using 'first' or 'second' -> Option A
  4. Quick Check:

    buildEither only accepts first or second = C [OK]
Hint: Use only first or second parameters with buildEither [OK]
Common Mistakes:
  • Trying to add unsupported parameter names
  • Ignoring static keyword requirements
  • Assuming code runs without error
5. How can you use 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?
hard
A. Use buildOptional to wrap guest mode view, and buildEither to choose between logged in and guest
B. Use buildEither to wrap guest mode view, and buildOptional to choose between logged in and guest
C. Use only buildOptional for all conditions
D. Use only buildEither for all conditions

Solution

  1. Step 1: Understand the conditions

    We have three cases: logged in, guest mode, and neither. buildEither can choose between logged in and guest mode views.
  2. Step 2: Use buildOptional for the third case

    The third case (neither) means no view, so wrap the guest mode view in buildOptional to include it only if guest mode is enabled.
  3. Step 3: Combine both builders

    Use buildEither to select logged in or guest mode, and buildOptional to skip guest mode if disabled, resulting in no view if neither condition is true.
  4. Final Answer:

    Use buildOptional to wrap guest mode view, and buildEither to choose between logged in and guest -> Option A
  5. Quick Check:

    buildOptional wraps optional guest, buildEither picks logged in or guest = D [OK]
Hint: buildEither picks branches; buildOptional skips optional parts [OK]
Common Mistakes:
  • Using buildEither alone for optional skipping
  • Using buildOptional alone for branching
  • Not handling the 'no view' case properly
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard