Skip to content

Instantly share code, notes, and snippets.

@LePips
Created November 18, 2023 01:48
Show Gist options
  • Save LePips/293d92f5fac07de256878e37e96e7bec to your computer and use it in GitHub Desktop.
Save LePips/293d92f5fac07de256878e37e96e7bec to your computer and use it in GitHub Desktop.
Swift ArrayBuilder resultBuilder
// Use to create an Array of elements in a result builder
//
// Best used with a typealias:
// typealias StringBuilder = ArrayBuilder<String>
@resultBuilder
public struct ArrayBuilder<Element> {
public static func buildBlock(_ components: [Element]...) -> [Element] {
components.flatMap { $0 }
}
public static func buildExpression(_ expression: Element) -> [Element] {
[expression]
}
public static func buildOptional(_ component: [Element]?) -> [Element] {
component ?? []
}
public static func buildEither(first component: [Element]) -> [Element] {
component
}
public static func buildEither(second component: [Element]) -> [Element] {
component
}
public static func buildArray(_ components: [[Element]]) -> [Element] {
components.flatMap { $0 }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment