Challenge - 5 Problems
Swift BuildBlock Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
What is the output of this Swift code using @resultBuilder?
Consider the following Swift code that uses a custom @resultBuilder named
ResultCombiner. What will be printed when combineResults() is called?Swift
import Foundation @resultBuilder struct ResultCombiner { static func buildBlock(_ components: String...) -> String { components.joined(separator: ", ") } } func combineResults() -> String { @ResultCombiner var result: String { "Hello" "World" "Swift" } return result } print(combineResults())
Attempts:
2 left
💡 Hint
Look at how the buildBlock function joins the components.
✗ Incorrect
The buildBlock function receives all components as an array of strings and joins them with a comma and space separator. So the output is the three strings joined by ", ".
🧠 Conceptual
intermediate1:30remaining
What does the buildBlock function do in a Swift result builder?
In Swift's result builder, what is the main role of the
buildBlock static function?Attempts:
2 left
💡 Hint
Think about how multiple parts are combined into one output.
✗ Incorrect
buildBlock takes multiple components and combines them into one final value that the result builder returns.
🔧 Debug
advanced2:00remaining
Why does this buildBlock implementation cause a compile error?
Examine this buildBlock function inside a Swift result builder. Why does it cause a compile error?
static func buildBlock(_ components: String) -> String {
components + "!"
}Swift
static func buildBlock(_ components: String) -> String { components + "!" }
Attempts:
2 left
💡 Hint
Check the parameter type expected by buildBlock.
✗ Incorrect
buildBlock is called with multiple components, so it must accept a variadic parameter (e.g., String...) instead of a single String.
📝 Syntax
advanced2:00remaining
Which buildBlock implementation correctly combines Int values into their sum?
You want to create a buildBlock function that sums all Int components passed to it. Which option is correct?
Attempts:
2 left
💡 Hint
Check parameter syntax and method names for summing arrays.
✗ Incorrect
Option C correctly uses a variadic parameter and the standard reduce method to sum the integers.
🚀 Application
expert3:00remaining
How to combine optional String results safely in buildBlock?
You want to combine multiple optional String components in buildBlock, ignoring nil values and joining non-nil with ", ". Which implementation achieves this?
Attempts:
2 left
💡 Hint
Consider how to safely unwrap optionals and skip nils.
✗ Incorrect
Option A uses compactMap to remove nils and then joins the remaining strings with ", ". Option A includes empty strings for nils, C is invalid because joined cannot be called on [String?], and D force unwraps optionals causing runtime error if nil.