Swift’s Result Builders
TupleViews and more!
--
Difficulty: Beginner | Easy | Normal | Challenging
This article has been developed using Xcode 14.2, and Swift 5.7.2
Prerequisites:
You need to be able to code in Swift, perhaps using Playgrounds and be able to use SwiftUI
Terminology
@resultBuilder: An attribute that transforms a sequence of statements into a single combined value
TupleView: A View created from a swift tuple of View values
Tuple: A group of zero or more values represented as a single compound value
Type: A representation of the type of data that can be processed, for example Integer or String
Variadric parameters: A parameter for a function that accepts zero or more values of the specified type
Result builders: The prerequisites
We need to understand a number of things to be able to fully understand
Tuples…from the beginning
I’ve already written about Tuples in a previous article as they allow you to store multiple values in a single variable.
Something like var person = (“Steve”, 22)
will do it in code. As you can see two elements are stored in the property called person
.
TupleView (represents a view)
A TupleView is a concrete SwiftUI View
type that stores multiple View
.
It is used internally by SwiftUI when combining views but developers typically do not interact with this type directly.
However you *can* use a TupleView
and you might create a ContentView
that shows the Words “Hello” and “World” on two different lines as they are contained within a VStack
.
struct ContentView: View {
var body: some View {
VStack {
TupleView((Text("Hello"),Text("World")))
}
}
}
A look at VStack
We can use TupleView
and @resultBuilder
to look at VStack
(and how similar views) work under the hood. This also gives a first opportunity to look at result…