Created
August 27, 2020 00:38
-
-
Save bok-/12b69ebf2232eb34fc7e78f726340c6f to your computer and use it in GitHub Desktop.
Genericised @_functionBuilder that appends to mutable collections
This file contains hidden or 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
@_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) | |
} | |
} | |
} |
This file contains hidden or 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
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