📖 Scenario: You are creating a simple Swift function that builds a message based on optional and conditional values.
🎯 Goal: Build a Swift function that uses BuildOptional and BuildEither to conditionally create parts of a message.
📋 What You'll Learn
Create an optional string variable called optionalPart with the value "Optional part included."
Create a boolean variable called includeFirst set to true
Use BuildOptional to include optionalPart only if it is not nil
Use BuildEither to choose between two strings based on includeFirst
Print the final combined message
💡 Why This Matters
🌍 Real World
Result builders like <code>BuildOptional</code> and <code>BuildEither</code> help Swift developers write clean, readable code for building UI views, DSLs, or complex strings with conditional parts.
💼 Career
Understanding these concepts is useful for Swift developers working on SwiftUI apps or any code that benefits from declarative and conditional building patterns.
Progress0 / 4 steps
1
Create the optional string variable
Create an optional string variable called optionalPart and set it to "Optional part included."
Swift
Hint
Use let optionalPart: String? = "Optional part included." to create the optional string.
2
Create the boolean variable
Create a boolean variable called includeFirst and set it to true
Swift
Hint
Use let includeFirst: Bool = true to create the boolean variable.
3
Use BuildOptional and BuildEither to build message parts
Use BuildOptional to include optionalPart only if it is not nil, and use BuildEither to choose between "First part included." and "Second part included." based on includeFirst. Store the combined message in a variable called message.
Swift
Hint
Define a @resultBuilder called MessageBuilder with buildOptional and buildEither methods. Use it in buildMessage() to conditionally add parts.
4
Print the final message
Write a print statement to display the variable message
Swift
Hint
Use print(message) to display the final combined message.
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
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.
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.
Final Answer:
To wrap optional code blocks so they can be included or skipped -> Option B
The code calls buildEither(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 D
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
Step 1: Identify the method call
The code calls buildEither(third: "Oops"), but only first and second parameters exist.
Step 2: Understand the fix
To fix, replace third with either first or second to match the defined overloads.
Final Answer:
Error: No 'third' parameter; fix by using 'first' or 'second' -> Option A
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
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.
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.
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.
Final Answer:
Use buildOptional to wrap guest mode view, and buildEither to choose between logged in and guest -> Option A
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 unknownstrongwhile earning +1 Grip toward your certificate.