Skip to content

Instantly share code, notes, and snippets.

@CraigSiemens
Last active September 15, 2022 01:55
Show Gist options
  • Save CraigSiemens/8c32d833fd585bdb897087ce5e2bd5e9 to your computer and use it in GitHub Desktop.
Save CraigSiemens/8c32d833fd585bdb897087ce5e2bd5e9 to your computer and use it in GitHub Desktop.
An simple example of using resultBuilder to create an Array.
@resultBuilder
struct ArrayBuilder<Element> {
static func buildBlock(_ components: [Element]...) -> [Element] {
components.flatMap { $0 }
}
static func buildExpression(_ expression: Element) -> [Element] {
[expression]
}
static func buildEither(first component: [Element]) -> [Element] {
component
}
static func buildEither(second component: [Element]) -> [Element] {
component
}
static func buildArray(_ components: [[Element]]) -> [Element] {
components.flatMap { $0 }
}
static func buildOptional(_ component: [Element]?) -> [Element] {
component ?? []
}
static func buildLimitedAvailability(_ component: [Element]) -> [Element] {
component
}
}
extension Array {
init(@ArrayBuilder<Element> content: () -> [Element]) {
self = content()
}
static func build(@ArrayBuilder<Element> content: () -> [Element]) -> Self {
content()
}
}
// An Example of not using the result builder to make and array.
let shouldWave = true
let isDaytime = true
let names = ["Alice", "Bob"]
var greetingParts = [
"Hello",
"World"
]
if shouldWave {
greetingParts.append("πŸ‘‹")
}
if isDaytime {
greetingParts.append("β˜€οΈ")
} else {
greetingParts.append("πŸŒ™")
}
for name in names {
greetingParts.append(name)
}
if #available(iOS 14.0, *) {
greetingParts.append("πŸ†•")
}
print(greetingParts) // ["Hello", "World", "πŸ‘‹", "β˜€οΈ", "Alice", "Bob", "πŸ†•"]
// An Example of using the result builder to make an array.
let shouldWave = true
let isDaytime = true
let names = ["Alice", "Bob"]
let greetingParts = Array {
"Hello"
"World"
if shouldWave {
"πŸ‘‹"
}
if isDaytime {
"β˜€οΈ"
} else {
"πŸŒ™"
}
for name in names {
name
}
if #available(iOS 14.0, *) {
"πŸ†•"
}
}
print(greetingParts) // ["Hello", "World", "πŸ‘‹", "β˜€οΈ", "Alice", "Bob", "πŸ†•"]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment