Avatar
Result Builder @resultBuilder struct ArrayBuilder<Element> { static func buildExpression(_ expression: Element) -> [Element] { // 2 -> [2] [expression] } static func buildBlock(_ components: [Element]...) -> [Element] { // [[2, 3, 4], [5, 6]] -> [2, 3, 4 ,5, 6] components.flatMap { $0 } } static func buildOptional(_ component: [Element]?) -> [Element] { component ?? [] } static func buildEither(first component: [Element]) -> [Element] { component } static func buildEither(second component: [Element]) -> [Element] { component } static func buildArray(_ components: [[Element]]) -> [Element] { // [[7], [8], [9], [10]] -> [7, 8, 9, 10] components.flatMap { $0 } } } extension Array { init(@ArrayBuilder<Element> builder: () -> [Element]) { self = builder() } } //let array: [Int] = .init { // [2, 3, 6] //} let array: [Int] = .init { 2 // [2] 3 // [3] if Bool.random() { 4 // [4] 5 // [5] } else { 0 0 } // [4, 5] 6 // [6] for i in 7 ... 10 { if i.isMultiple(of: 2) { i // [i] } } // [8, 10] } print(array)