0
0
Swiftprogramming~10 mins

@resultBuilder attribute in Swift - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete 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'
Amain
BpropertyWrapper
CresultBuilder
Davailable
Attempts:
3 left
💡 Hint
Common Mistakes
Using '@propertyWrapper' instead of '@resultBuilder'.
Forgetting the '@' symbol before 'resultBuilder'.
2fill in blank
medium

Complete 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'
Aprint
Breturn
Cyield
Dlet
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.
3fill in blank
hard

Fix 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'
A...
C...Int...
D...Int
Attempts:
3 left
💡 Hint
Common Mistakes
Writing '...Int' which is invalid syntax.
Using '...Int...' which is not valid.
4fill in blank
hard

Fill 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'
A...
B.joined(
C)
D.joined
Attempts:
3 left
💡 Hint
Common Mistakes
Using parentheses incorrectly around 'joined'.
Forgetting the variadic '...'.
5fill in blank
hard

Fill 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'
A...
Bcomponent
Cjoined
Dcomponents
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.