Skip to content

Instantly share code, notes, and snippets.

@dehrom
Created October 3, 2024 21:43
Show Gist options
  • Save dehrom/83da8c6323a6ba914da282257ff2d211 to your computer and use it in GitHub Desktop.
Save dehrom/83da8c6323a6ba914da282257ff2d211 to your computer and use it in GitHub Desktop.
import Foundation
@resultBuilder
public struct ArrayBuilder<T> {
public static func buildBlock() -> [T] { [] }
public static func buildExpression(_ expression: T) -> [T] { [expression] }
public static func buildExpression(_ expression: T...) -> [T] { expression }
public static func buildExpression(_ expression: T?...) -> [T] { expression.compactMap { $0 } }
public static func buildExpression(_ expression: T?) -> [T] { [expression].compactMap { $0 } }
public static func buildExpression(_ expression: [T]) -> [T] { expression }
public static func buildBlock(_ components: [T]...) -> [T] { components.flatMap { $0 } }
public static func buildArray(_ components: [[T]]) -> [T] { components.flatMap { $0 } }
public static func buildOptional(_ component: [T?]) -> [T] { component.compactMap { $0 } }
public static func buildOptional(_ component: [T]?) -> [T] { component ?? [] }
public static func buildEither(first component: T) -> [T] { [component] }
public static func buildEither(second component: T) -> [T] { [component] }
public static func buildEither(first component: [T]) -> [T] { component }
public static func buildEither(second component: [T]) -> [T] { component }
public static func buildPartialBlock(first: [T]) -> [T] { first }
public static func buildPartialBlock(accumulated: [T], next: [T]) -> [T] { accumulated + next }
public static func buildLimitedAvailability(_ component: [T]) -> [T] { component }
public static func buildFinalResult(_ component: [T]) -> [T] { component }
}
extension Array {
public init(@ArrayBuilder<Element> builder: () -> [Element]) {
self = builder()
}
}
let flag = true
let array = Array {
if flag {
"value 0"
}
"value 1"
["value 2", "value 3"]
nil
}
print(array) // ["value 0", "value 1", "value 2", "value 3"]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment