What if you could replace tangled if-else checks with clean, simple building blocks for choices and options?
Why BuildOptional and buildEither in Swift? - Purpose & Use Cases
Imagine you are writing code to handle different choices or optional values manually, like checking if a value exists or deciding between two options with many if-else statements.
This manual approach quickly becomes messy and hard to read. You might forget a case, write repetitive code, or introduce bugs because the logic is scattered and unclear.
BuildOptional and buildEither let you cleanly and clearly express optional and either-or choices in your code. They help you build these decisions in a structured way, making your code easier to write, read, and maintain.
if let value = optionalValue { // handle value } else { // handle no value } if condition { // do A } else { // do B }
buildOptional { value }
buildEither(first: A)
buildEither(second: B)You can express complex optional and choice logic in a simple, clear, and reusable way that scales well as your code grows.
Think about a form where a user can optionally enter a phone number, or choose between email or phone contact methods. BuildOptional and buildEither help you handle these choices cleanly in your code.
Manual checks for options and choices get messy fast.
BuildOptional and buildEither provide a neat way to express these decisions.
This leads to clearer, safer, and easier-to-maintain code.
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
