Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning multiple View objects from a closure in Swift [duplicate]

I often see code like this:

VStack {
  Text("A")
  Text("B")
}

From looking at the swift tutorials, I know that this is shorthand for specifying a closure as the last parameter to a function. However, afaik if the return keyword is not specified, a closure will implicitly return the result of the expression inside.

In this case, there are two Text objects. Are they returned as a tuple or a list? I know it works, but its unclear to me, what exactly is being returned from the closure.

like image 981
Benjamin Tamasi Avatar asked Apr 24 '26 05:04

Benjamin Tamasi


2 Answers

The initial ability to omit the return statement was introduced in Swift Evolution 255 - This change only allowed for a single return value. In fact, the ability to return multiple values was considered in this proposal and discarded.

The structure you are asking about was originally introduced by Apple as a private implementation to support SwiftUI but has now been officially adopted in Swift Evolution 289 - Function Builders.

By referring to the introduction section of that document you can see that the values are, indeed, returned as a tuple.

// Original source code:
@TupleBuilder
func build() -> (Int, Int, Int) {
  1
  2
  3
}

// This code is interpreted exactly as if it were this code:
func build() -> (Int, Int, Int) {
  let _a = TupleBuilder.buildExpression(1)
  let _b = TupleBuilder.buildExpression(2)
  let _c = TupleBuilder.buildExpression(3)
  return TupleBuilder.buildBlock(_a, _b, _c)
}
like image 174
Paulw11 Avatar answered Apr 26 '26 23:04

Paulw11


SwiftUI automatically returns the two Text’s in a type of TupleView. Swift’s resultBuilder is the magic, which was SE0289: https://github.com/apple/swift-evolution/blob/main/proposals/0289-result-builders.md

like image 44
Shadowrun Avatar answered Apr 26 '26 23:04

Shadowrun