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
}

Last updated