What's `let _ = foo()` vs `_ = foo()`

It appears the second form is Void, and it can be used anywhere the first form can. Except not in SwiftUI ViewBuilder.

What is the second form? Why is it allowed?

Edit: it appears the two expressions generate exactly the same instructions:

with -O the two are just no-op with my test code.

:thinking: all the more strange that let _ = foo() is allowed in ViewBuilder expression but not _ = foo() if they are the same.

Anyone know what's going on? Is this an oversight with the ResultBuilder syntax?

Edit 2: After reading the Language Reference: _ is "Wildcard Expression", which can be used in many contexts.

_ = foo()     // this is assignment, is not allowed in ResultBuilder expression

let _ = foo()  // this is `let` variable declaration, is allowed in ResultBuilder expression

Two different things.

They are the same. The second form shall still work in SwiftUI:

_ = foo()
return Text("Hello") // return here is needed

let _ = foo()
Text("Hello") // return here is not needed (but possible)
1 Like

The first one is not a ViewBuilder. I believe _ = foo() should be allowed in ViewBuilder expression since the two are the same.

1 Like

Even thought they happen to be the same thing in practice (except when they're not), one is an assignment, and the other is a declaration (and an assignment).

Consider:

someVar = foo()
// vs.
let someVar = foo()

The former is assigning the return value of foo() into an existing (mutable) variable someVar. The latter is declaring a new (possibly shadowing an existing) let and the doing the assignment.

In the case when someVar is replaced with _, the two are really the same. Kinda. At least the effect is the same. But to the source code parser, they're not the same, methinks.

And view builders happen to support declarations, but not assignments. I guess it should be possible to special case the _ assignment, but I guess no-one has implemented that yet.