Normally, the following code cannot be compiled.
let a = 3
if let b = a { // ❌Error: Initializer for conditional binding must have Optional type, not 'Int'
...
}
But if we define a resultBuilder and implement buildOptional method, similar code can be compiled.
@resultBuilder
enum XBuilder {
static func buildBlock(_: Int...) -> Int {
0
}
static func buildOptional(_: Int?) -> Int {
1
}
}
func test(@XBuilder content: () -> Int) -> Int {
content()
}
let a = 3
_ = test {
if let b = a {
b
}
}
Is this the expected behavior of resultBuilder or a bug? Can anyone help me explain this grammar?
Test it on swift-5.6 and swift-5.7. (Unlikely to be related to SE0345)
Original Context
Found this strange grammar when coding with SwiftUI.
struct ContentView: View {
@State var enable = true
var body: some View {
VStack {
if let e = enable { // ✅ Working
Text("")
.onAppear {
test1() // ❌ Not working
test2 { // ✅ Working
if let e = $enable {
Text("1")
}
}
}
}
}
}
@ViewBuilder
func test1() -> some View{
if let e = $enable {
Text("")
}
}
func test2(@ViewBuilder content: () -> some View) -> some View{
content()
}
}