Bird
Raised Fist0
Swiftprogramming~20 mins

Custom result builder declaration in Swift - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Swift Result Builder Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
What is the output of this Swift code using a custom result builder?
Consider the following Swift code that uses a custom result builder named StringListBuilder. What will be printed when print(buildList()) is called?
Swift
import Foundation

@resultBuilder
struct StringListBuilder {
    static func buildBlock(_ components: String...) -> [String] {
        return components
    }
}

func buildList() -> [String] {
    StringListBuilder.buildBlock(
        "apple",
        "banana",
        "cherry"
    )
}

print(buildList())
A["apple", "banana", "cherry"]
B"applebanana cherry"
C["apple banana cherry"]
DSyntaxError
Attempts:
2 left
💡 Hint
Look at how the buildBlock method collects its string components into an array.
❓ Predict Output
intermediate
2:00remaining
What error does this Swift custom result builder code produce?
Given this Swift code with a custom result builder, what error will occur when compiling?
Swift
@resultBuilder
struct IntBuilder {
    static func buildBlock(_ components: Int...) -> Int {
        components.reduce(0, +)
    }
}

func buildSum() -> Int {
    IntBuilder.buildBlock(
        1,
        2,
        "3"
    )
}

print(buildSum())
AOutput: 6
BRuntimeError: Cannot add String to Int
CTypeError: Cannot convert value of type 'String' to expected argument type 'Int'
DSyntaxError: Missing colon
Attempts:
2 left
💡 Hint
Check the types of the arguments passed to buildBlock.
🧠 Conceptual
advanced
2:00remaining
Which option correctly implements a custom result builder that supports optional components?
You want to create a custom result builder that can handle optional strings, including them only if they are non-nil. Which implementation of buildOptional is correct?
A
static func buildOptional(_ component: String?) -> [String] {
    if component != nil { return [component!] } else { return [""] }
}
B
static func buildOptional(_ component: String?) -> [String] {
    component.map { [$0] } ?? []
}
C
static func buildOptional(_ component: String?) -> String {
    component ?? ""
}
D
static func buildOptional(_ component: String?) -> [String] {
    [component!]
}
Attempts:
2 left
💡 Hint
Think about safely unwrapping optionals and returning an empty array if nil.
❓ Predict Output
advanced
2:00remaining
What is the output of this Swift custom result builder code?
Given this Swift code with a custom result builder, what will be printed when print(buildNumber(condition: true)) is called?
Swift
@resultBuilder
struct NumberBuilder {
    static func buildBlock(_ components: Int...) -> Int {
        components.reduce(0, +)
    }

    static func buildEither(first component: Int) -> Int {
        component
    }

    static func buildEither(second component: Int) -> Int {
        component
    }
}

func buildNumber(condition: Bool) -> Int {
    NumberBuilder.buildBlock(
        1,
        condition ? NumberBuilder.buildEither(first: 2) : NumberBuilder.buildEither(second: 3),
        4
    )
}

print(buildNumber(condition: true))
AError: Missing buildOptional method
BOutput: 10
CError: Cannot convert value of type 'Int' to expected argument type '[Int]'
DOutput: 7
Attempts:
2 left
💡 Hint
The ternary selects the first branch (2) when condition is true. Sum 1 + 2 + 4.
🚀 Application
expert
3:00remaining
How many items are in the resulting array from this custom result builder usage?
Given this Swift code with a custom result builder that supports conditionals and optionals, how many strings are in the array returned by buildMenu(showDessert: true)?
Swift
@resultBuilder
struct MenuBuilder {
    static func buildBlock(_ components: [String]...) -> [String] {
        components.flatMap { $0 }
    }

    static func buildOptional(_ component: [String]?) -> [String] {
        component ?? []
    }

    static func buildEither(first component: [String]) -> [String] {
        component
    }

    static func buildEither(second component: [String]) -> [String] {
        component
    }
}

func buildMenu(showDessert: Bool) -> [String] {
    MenuBuilder.buildBlock(
        ["Salad", "Soup"],
        showDessert ? MenuBuilder.buildEither(first: ["Cake"]) : MenuBuilder.buildEither(second: []),
        MenuBuilder.buildOptional(nil)
    )
}

let menu = buildMenu(showDessert: true)
print(menu.count)
A3
B2
C4
D1
Attempts:
2 left
💡 Hint
Count all strings included by the builder, including conditionals and optionals.

Practice

(1/5)
1. What is the main purpose of declaring a @resultBuilder in Swift?
easy
A. To handle errors automatically in functions
B. To create a new data type like a class or struct
C. To optimize memory usage during runtime
D. To define how multiple code parts combine into a single result

Solution

  1. Step 1: Understand the role of @resultBuilder

    A @resultBuilder is used to customize how multiple code blocks combine into one result, making code cleaner.
  2. Step 2: Compare with other options

    Options A, B, and D describe unrelated concepts like error handling, data types, and optimization, which are not the purpose of result builders.
  3. Final Answer:

    To define how multiple code parts combine into a single result -> Option D
  4. Quick Check:

    Result builder = combine code parts [OK]
Hint: Result builders combine code parts into one result [OK]
Common Mistakes:
  • Confusing result builders with classes or structs
  • Thinking result builders handle errors
  • Assuming result builders optimize memory
2. Which of the following is the correct way to start declaring a custom result builder in Swift?
easy
A. @resultBuilder struct MyBuilder { static func buildBlock() -> String { "" } }
B. @resultBuilder class MyBuilder { func buildBlock() {} }
C. class MyBuilder { func buildBlock() -> Int { 0 } }
D. struct MyBuilder { static func buildBlock() {} }

Solution

  1. Step 1: Identify correct syntax for result builder

    A custom result builder must be declared with @resultBuilder attribute on a struct, and have static methods like buildBlock returning a value.
  2. Step 2: Check each option

    @resultBuilder struct MyBuilder { static func buildBlock() -> String { "" } } correctly uses @resultBuilder, declares a struct, and has a static buildBlock method returning a String. The other options miss the attribute, use class instead of struct, or have non-static buildBlock.
  3. Final Answer:

    @resultBuilder struct MyBuilder { static func buildBlock() -> String { "" } } -> Option A
  4. Quick Check:

    Result builder = @resultBuilder + struct + static methods [OK]
Hint: Use @resultBuilder on a struct with static buildBlock method [OK]
Common Mistakes:
  • Using class instead of struct for result builder
  • Forgetting the @resultBuilder attribute
  • Making buildBlock non-static
3. Given this custom result builder and usage, what is the output?
 @resultBuilder
struct IntSumBuilder {
    static func buildBlock(_ numbers: Int...) -> Int {
        numbers.reduce(0, +)
    }
}

func sum(@IntSumBuilder _ content: () -> Int) -> Int {
    content()
}

let result = sum {
    5
    10
    3
}
print(result)
medium
A. 5103
B. 18
C. Error: buildBlock requires array
D. 0

Solution

  1. Step 1: Understand buildBlock behavior

    The buildBlock method takes multiple Int values and sums them using reduce(0, +).
  2. Step 2: Evaluate the sum call

    The closure passed to sum returns three Int values: 5, 10, and 3. The builder sums them: 5 + 10 + 3 = 18.
  3. Final Answer:

    18 -> Option B
  4. Quick Check:

    Sum of 5, 10, 3 = 18 [OK]
Hint: buildBlock sums all Int inputs passed in closure [OK]
Common Mistakes:
  • Thinking values concatenate as strings
  • Expecting buildBlock to receive an array instead of variadic
  • Confusing output with zero or error
4. Identify the error in this custom result builder declaration:
 @resultBuilder
struct TextBuilder {
    func buildBlock(_ components: String...) -> String {
        components.joined(separator: ", ")
    }
}
medium
A. buildBlock must be static
B. buildBlock must return Int
C. struct cannot be used with @resultBuilder
D. buildBlock cannot take variadic parameters

Solution

  1. Step 1: Check method requirements in result builder

    Methods like buildBlock inside a @resultBuilder must be declared as static so they can be called without an instance.
  2. Step 2: Analyze the given code

    The buildBlock method is missing the static keyword, which causes a compile error.
  3. Final Answer:

    buildBlock must be static -> Option A
  4. Quick Check:

    buildBlock method = static [OK]
Hint: buildBlock must always be static in result builders [OK]
Common Mistakes:
  • Omitting static keyword on buildBlock
  • Thinking buildBlock must return Int always
  • Believing struct can't be used with @resultBuilder
5. You want to create a custom result builder that builds a dictionary from key-value pairs written inside a closure. Which of the following buildBlock implementations correctly combines multiple (String, Int) tuples into a single dictionary?
hard
A. static func buildBlock(_ pairs: (String, Int)...) -> [String: Int] { pairs.map { [$0.0: $0.1] } }
B. static func buildBlock(_ pairs: [(String, Int)]) -> [String: Int] { pairs.reduce([:]) { $0 + $1 } }
C. static func buildBlock(_ pairs: (String, Int)...) -> [String: Int] { Dictionary(uniqueKeysWithValues: pairs) }
D. static func buildBlock(_ pairs: (String, Int)...) -> [(String, Int)] { pairs }

Solution

  1. Step 1: Understand the goal

    The builder should combine multiple key-value pairs into a single dictionary.
  2. Step 2: Analyze each option

    static func buildBlock(_ pairs: (String, Int)...) -> [String: Int] { Dictionary(uniqueKeysWithValues: pairs) } uses Dictionary(uniqueKeysWithValues:) which correctly creates a dictionary from tuples. static func buildBlock(_ pairs: [(String, Int)]) -> [String: Int] { pairs.reduce([:]) { $0 + $1 } } tries to reduce with + which is invalid for dictionaries. static func buildBlock(_ pairs: (String, Int)...) -> [String: Int] { pairs.map { [$0.0: $0.1] } } maps to an array of dictionaries, not a single dictionary. static func buildBlock(_ pairs: (String, Int)...) -> [(String, Int)] { pairs } returns an array of tuples, not a dictionary.
  3. Final Answer:

    static func buildBlock(_ pairs: (String, Int)...) -> [String: Int] { Dictionary(uniqueKeysWithValues: pairs) } -> Option C
  4. Quick Check:

    Use Dictionary(uniqueKeysWithValues:) to combine tuples [OK]
Hint: Use Dictionary(uniqueKeysWithValues:) to build dictionary from tuples [OK]
Common Mistakes:
  • Returning array of dictionaries instead of one dictionary
  • Using invalid + operator to combine dictionaries
  • Returning array of tuples instead of dictionary
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard