result-building methods
Swift โฉ Attributes โฉ Result Builders โฉ
่ฆๅ๏ผ็ฑๆๅ
งๅฑคๅพๅคๅๆบฏ โญ๏ธ
------------------------------
โข ๆๅ
งๅฑค ๏ผbuild Expression
โข ้ๅฐ {} ๏ผbuild Block
โข ้ๅฐ if ๏ผbuild 1st / Optional
โข ้ๅฐ else๏ผbuild 2nd
โข ้ๅฐ for ๏ผbuild Array
Expression : type of the result builderโs input.
Component : type of a partial result.
FinalResult : type of the result that the result builder produces.
Expression / FinalResult = Component by default.
@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
}
SE0289 (Result Builder) โฉ result-building methods โญ๏ธ (๐ธ ๅฎ็พฉ)
Swift Reference โฉ Attributes โฉ Declaration Attributes โฉ resultBuilder โญ๏ธ
An example to callbuildLimitedAvailability(_:)
method can be found in Swift Reference.
ๅจ Swift Reference ็ฏไพไธญ๏ผๆๅจ result-building method ๅ งไฝฟ็จ guard let ็ๆ ๆณ (ๅฆไธ)ใๆไปฅ โญ๏ธ ้้ปไบๆๆ็ใไธ่ฝไฝฟ็จ guardใๆ่ฉฒไธๆฏๆๅจ้ไบ result-building methods ไธญ๏ผ่ๆฏๆไฝฟ็จ้ๅ result builder ็ (closure) block ๅ ง้จไธ่ฝไฝฟ็จใ
static func buildOptional(_ component: Component?) -> Component {
// โญ๏ธ guard let
guard let component = component else { return [] }
return component
}
Last updated