0
0
Swiftprogramming~10 mins

Why result builders enable DSLs in Swift - Test Your Understanding

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

Complete the code to define a simple result builder attribute.

Swift
@resultBuilder
struct [1] {
    static func buildBlock(_ components: String...) -> String {
        components.joined(separator: ", ")
    }
}
Drag options to blanks, or click blank then click option'
AMyBuilder
BbuildBlock
CResultBuilder
DDSLBuilder
Attempts:
3 left
💡 Hint
Common Mistakes
Using a function name instead of a struct name.
Using a reserved keyword as the builder name.
2fill in blank
medium

Complete the code to apply the result builder to a function.

Swift
func buildList(@[1] content: () -> String) -> String {
    content()
}
Drag options to blanks, or click blank then click option'
ADSLBuilder
BResultBuilder
CMyBuilder
DbuildBlock
Attempts:
3 left
💡 Hint
Common Mistakes
Using a function name instead of the builder name.
Omitting the '@' symbol before the builder name.
3fill in blank
hard

Fix the error in the result builder usage by completing the code.

Swift
let result = buildList {
    "Hello"
    [1] "World"
}
Drag options to blanks, or click blank then click option'
A+
B-
C;
D,
Attempts:
3 left
💡 Hint
Common Mistakes
Using '+' to concatenate strings inside the builder closure.
Using semicolons which are not needed here.
4fill in blank
hard

Fill both blanks to create a DSL-like syntax that builds a list of items.

Swift
let list = buildList {
    [1] "Apple"
    [2] "Banana"
}
Drag options to blanks, or click blank then click option'
A"Orange"
B"Grape"
C,
D;
Attempts:
3 left
💡 Hint
Common Mistakes
Using semicolons instead of commas.
Not adding a string literal in the first blank.
5fill in blank
hard

Fill all three blanks to define a result builder that combines strings with spaces and use it in a function.

Swift
@resultBuilder
struct [1] {
    static func buildBlock(_ components: String...) -> String {
        components[2]separator: " "[3]
    }
}

func greet(@MyBuilder content: () -> String) -> String {
    content()
}
Drag options to blanks, or click blank then click option'
AMyBuilder
Bjoined
C()
DbuildBlock
Attempts:
3 left
💡 Hint
Common Mistakes
Using incorrect struct name that doesn't match the attribute.
Omitting parentheses after 'joined'.