Created
January 27, 2021 17:55
-
-
Save dreymonde/98d73932efa5441acf55cd2853cdeb91 to your computer and use it in GitHub Desktop.
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
// THIS IS A UNIVERSAL SWIFT FUNCTION BIULDER | |
// FOR ARRAYS OF ANY TYPE | |
// tested on Swift 5.3.1 | |
@_functionBuilder | |
public enum ArrayBuilder<Element> { | |
public typealias Expression = Element | |
public typealias Component = [Element] | |
public static func buildExpression(_ expression: Expression) -> Component { | |
[expression] | |
} | |
public static func buildExpression(_ expression: Expression?) -> Component { | |
expression.map({ [$0] }) ?? [] | |
} | |
public static func buildBlock(_ children: Component...) -> Component { | |
children.flatMap({ $0 }) | |
} | |
public static func buildOptional(_ children: Component?) -> Component { | |
children ?? [] | |
} | |
public static func buildBlock(_ component: Component) -> Component { | |
component | |
} | |
public static func buildEither(first child: Component) -> Component { | |
child | |
} | |
public static func buildEither(second child: Component) -> Component { | |
child | |
} | |
} | |
// USAGE EXAMPLE: | |
struct Schedule { | |
var entries: [Entry] | |
init(@ArrayBuilder<Entry> builder: () -> [Entry]) { | |
self.entries = builder() | |
} | |
} | |
// then use as you would expect: | |
let schedule = Schedule { | |
Entry1() | |
Entry2() | |
if someCondition() { | |
Entry3() | |
} else { | |
Entry4() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment