Skip to content

Instantly share code, notes, and snippets.

@nicholascross
Created June 16, 2021 22:35
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nicholascross/85260b01432cb937c7b61085ea7fed31 to your computer and use it in GitHub Desktop.
Save nicholascross/85260b01432cb937c7b61085ea7fed31 to your computer and use it in GitHub Desktop.
Generic array builder using swift 5.4 result builder
@resultBuilder
enum ArrayBuilder<OutputModel> {
static func buildEither(first component: [OutputModel]) -> [OutputModel] {
return component
}
static func buildEither(second component: [OutputModel]) -> [OutputModel] {
return component
}
static func buildOptional(_ component: [OutputModel]?) -> [OutputModel] {
return component ?? []
}
static func buildExpression(_ expression: OutputModel) -> [OutputModel] {
return [expression]
}
static func buildExpression(_ expression: ()) -> [OutputModel] {
return []
}
static func buildBlock(_ components: [OutputModel]...) -> [OutputModel] {
return components.flatMap { $0 }
}
static func buildArray(_ components: [[OutputModel]]) -> [OutputModel] {
Array(components.joined())
}
}
// Example usage
public struct OutputModel {
}
public struct ExampleTransform {
public init() {
}
@ArrayBuilder<OutputModel>
func transform() -> [OutputModel] {
OutputModel()
OutputModel()
if true {
OutputModel()
}
for _ in 0...3 {
OutputModel()
}
OutputModel()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment