-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathArrayBuild.swift
More file actions
59 lines (46 loc) · 1.59 KB
/
Copy pathArrayBuild.swift
File metadata and controls
59 lines (46 loc) · 1.59 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
//
// ArrayBuild.swift
// ListDemo
//
// Created by HumorousGhost on 2022/7/15.
//
import Foundation
public extension Array {
/// Builds an array from an @ArrayBuilder closure. Use `Array.build` if you're running into ambiguity issues.
init(@ArrayBuilder<Element> contents: () throws -> [Element]) rethrows {
self = try contents()
}
/// Builds an array from an @ArrayBuilder closure. Provided in addition to `init(contents:)` to avoid ambiguity.
static func build(@ArrayBuilder<Element> contents: () throws -> [Element]) rethrows -> Self {
try Self(contents: contents)
}
}
@resultBuilder
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
}
public static func buildArray(_ contents: [[Element]]) -> [Element] {
Array(contents.joined())
}
}