result-building methods
Swift ⟩ Attributes ⟩ Result Builders ⟩
規則:由最內層往外回溯 ⭐️
------------------------------
• 最內層 :build Expression
• 遇到 {} :build Block
• 遇到 if :build 1st / Optional
• 遇到 else:build 2nd
• 遇到 for :build Array
@resultBuilder
struct ExampleResultBuilder {
/// TYPE of individual statement expressions in the transformed function.
/// (default = `Component` if `buildExpression()` not provided)
typealias Expression = ...
/// TYPE of a partial result
/// (carried through all of the build methods)
typealias Component = ...
/// TYPE of the final returned result
/// (default = `Component` if `buildFinalResult()` not provided)
typealias FinalResult = ...
// --------------------------
// ⭐️ Required Methods
// --------------------------
/// 🔸 build combined results from statement blocks.
static func buildBlock(_ components: Component...) -> Component
// --------------------------
// ⭐️ Optional Methods
// --------------------------
/// 🔸 translate expression (contextual type) into partial result.
/// - If the result builder has `buildExpression(_:)` method(s),
/// each expression becomes a call to one of the method(s).
/// - This transformation is always first.
static func buildExpression(_ expression: Expression) -> Component
/// 🔸 support `if`, `optional chaining`.
static func buildOptional(_ component: Component?) -> Component
/// 🔸 support 'if-else' / 'switch'.
static func buildEither(first component: Component) -> Component
static func buildEither(second component: Component) -> Component
/// 🔸 support 'for..in'.
static func buildArray(_ components: [Component]) -> Component
/// 🔸 called on the partial result of an 'if #available' block
/// to allow the result builder to erase type information.
/// - happens before buildEither(first:/second:), buildOptional(_:)
static func buildLimitedAvailability(_ component: Component) -> Component
/// 🔸 called from the outermost block statement
/// to produce the final returned result.
static func buildFinalResult(_ component: Component) -> FinalResult
}
Last updated
Was this helpful?