Skip to content

Commit 193eed7

Browse files
committed
Add convenience initializer for if-else statements
1 parent ba64513 commit 193eed7

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
//===----------------------------------------------------------------------===//
2+
//
3+
// This source file is part of the Swift.org open source project
4+
//
5+
// Copyright (c) 2014 - 2022 Apple Inc. and the Swift project authors
6+
// Licensed under Apache License v2.0 with Runtime Library Exception
7+
//
8+
// See https://swift.org/LICENSE.txt for license information
9+
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
10+
//
11+
//===----------------------------------------------------------------------===//
12+
13+
import SwiftSyntax
14+
15+
public extension IfStmt {
16+
/// A convenience initializer that allows using builder closures to express an
17+
/// if statement, potentially with a second trailing builder closure for the else
18+
/// body.
19+
init(
20+
leadingTrivia: Trivia = [],
21+
conditions: ExpressibleAsConditionElementList,
22+
@CodeBlockItemListBuilder body: () -> ExpressibleAsCodeBlockItemList,
23+
@CodeBlockItemListBuilder elseBody: () -> ExpressibleAsCodeBlockItemList? = { nil }
24+
) {
25+
let generatedElseBody = elseBody()
26+
self.init(
27+
leadingTrivia: leadingTrivia,
28+
conditions: conditions,
29+
body: body(),
30+
elseKeyword: generatedElseBody == nil ? nil : SyntaxFactory.makeElseKeyword(leadingTrivia: .space, trailingTrivia: []),
31+
elseBody: generatedElseBody.map { CodeBlock(statements: $0) }
32+
)
33+
}
34+
}

0 commit comments

Comments
 (0)