Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to declare a simple result builder named Builder.
Swift
@[1] struct Builder { static func buildBlock(_ components: String...) -> String { components.joined(separator: ", ") } }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using '@propertyWrapper' instead of '@resultBuilder'.
Forgetting the '@' symbol before 'resultBuilder'.
✗ Incorrect
The @resultBuilder attribute is used to define a custom builder type that can combine multiple components into one result.
2fill in blank
mediumComplete the code to use the Builder result builder in a function.
Swift
@Builder
func buildText() -> String {
[1] "Hello"
"World"
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'yield' which is for generators, not result builders.
Using 'print' which outputs to console but does not return a value.
✗ Incorrect
Inside a function using a result builder, you use 'return' to provide components that the builder will combine.
3fill in blank
hardFix the error in the buildBlock method to correctly combine Int values.
Swift
@resultBuilder
struct IntBuilder {
static func buildBlock(_ components: Int[1]) -> Int {
components.reduce(0, +)
}
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Writing '...Int' which is invalid syntax.
Using '...Int...' which is not valid.
✗ Incorrect
The buildBlock method takes a variadic parameter of Ints, which is written as 'Int...'.
4fill in blank
hardFill both blanks to create a result builder that combines strings with a space.
Swift
@resultBuilder
struct SpaceBuilder {
static func buildBlock(_ components: String[1]) -> String {
components[2] separator: " "
}
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using parentheses incorrectly around 'joined'.
Forgetting the variadic '...'.
✗ Incorrect
The buildBlock method takes a variadic String parameter 'String...' and calls '.joined(separator: " ")' on the components.
5fill in blank
hardFill all three blanks to define a result builder that filters out empty strings and joins the rest with commas.
Swift
@resultBuilder
struct FilteredBuilder {
static func buildBlock(_ components: String[1]) -> String {
components.filter { [2].isEmpty == false }.[3](separator: ",")
}
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'components' inside the filter closure instead of the singular parameter.
Forgetting to use 'joined' method to combine strings.
✗ Incorrect
The buildBlock method takes a variadic String parameter 'String...'. The filter closure uses 'component.isEmpty == false' to exclude empty strings. Then it calls 'joined(separator: ",")' to combine the filtered strings.