Created
June 16, 2021 22:35
-
-
Save nicholascross/85260b01432cb937c7b61085ea7fed31 to your computer and use it in GitHub Desktop.
Generic array builder using swift 5.4 result builder
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@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