Skip to content

Instantly share code, notes, and snippets.

@bok-
Created August 27, 2020 00:38
Show Gist options
  • Save bok-/12b69ebf2232eb34fc7e78f726340c6f to your computer and use it in GitHub Desktop.
Save bok-/12b69ebf2232eb34fc7e78f726340c6f to your computer and use it in GitHub Desktop.
Genericised @_functionBuilder that appends to mutable collections
@_functionBuilder
public enum CollectionBuilder<Element>: SimpleBuilder {
public typealias Component = Element
}
public extension RangeReplaceableCollection {
mutating func collect (@CollectionBuilder<Element> _ builder: () -> Element) {
append(builder())
}
mutating func collect (@CollectionBuilder<Element> _ builder: () -> [Element]) {
append(contentsOf: builder())
}
}
public extension Set {
mutating func collect(@CollectionBuilder<Element> _ builder: () -> Element) {
insert(builder())
}
mutating func collect(@CollectionBuilder<Element> _ builder: () -> [Element]) {
for element in builder() {
insert(element)
}
}
}
public protocol SimpleBuilder {
associatedtype Component
}
public extension SimpleBuilder {
static func buildBlock () -> [Component] {
[]
}
static func buildBlock (_ child: Component) -> [Component] {
[child]
}
static func buildBlock (_ children: Component...) -> [Component] {
children
}
static func buildIf (_ children: Component?) -> [Component] {
guard let children = children else {
return []
}
return [children]
}
static func buildEither (first: Component) -> [Component] {
[first]
}
static func buildEither (second: Component) -> [Component] {
[second]
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment