
Have you ever wondered why there’s a limit of 10 child views in SwiftUI?
It’s not completely impossible, but it is a limit that Apple has imposed, most likely for performance reasons.
However, if you’ve never seen how ViewBuilder
works, this is a great way to see what it looks like under the surface. ViewBuilder
comes with 10 static functions called buildBlock
, each of which take a different number of generic parameters. We created a buildBlock
that takes a single generic parameter in yesterday’s Daily Coding Tip when creating the @ShapeBuilder
result builder, if you remember that.
Each generic parameter could be anything, as long as it conforms to the View
protocol.
If we had a single generic type for the buildBlock
, we would be forced to make all other children to be the same type, for instance Text
.
Here are all the new buildBlock
implementations from 11 to 15:
It’s interesting that although buildBlock
uses a TupleView
to return a single view that combines the children, there isn’t actually a limit of 10 with TupleView
. In other words we can continue to do exactly what Apple does, adding views inside of a TupleView
all the way to 15. I’m using a type that conforms to View
here, as this allows me to implictly use the ViewBuilder
result builder for the body property. The same would be true in a computed property with the opaque some View
return type, as long as it was explicitly given the @ViewBuilder
decoration.
Although it’s possible to build NumbersView
without a specific layout, I’ve used a VStack
to lay them out vertically in ContentView.
There might be better ways to do this in terms of performance, for example a TupleView
of two TupleViews
, each containing 10 child views:
Just remember that this buildBlock
can be used when there are exactly 20 child views, and you will need a buildBlock
for every number from 11 to 20 to make it fully useable.