Over the course of making several SwiftUI apps, I’ve discovered quite a few hidden magic of SwiftUI that are quite fun.
Here are 6 interesting SwiftUI features in View Builder many don’t know are even possible 🤯
View protocol with enum
Struct is not the only way to describe #SwiftUI views. Learn how you can achieve the same thing with just enum
Conform primitive type to View protocol
You can also conform any value type or primitive type to View protocol
The only requirement View needs is to yield a reasonable body.
Optional conforms to View as long as its Wrapped associated value conforms to View.
This means we can provide nil from ViewBuilder block. All the below declarations are valid.
some keyword is not required
some View is an opaque result type introduced in Swift 5.1 which conforms to View.
If you take a look at View protocol, Body is an associated type.
This means we can specify the return of body function with any concrete type conforming to View
Make a custom resultBuilder
The some keyword for opaque result type ensures returning a specific concrete type conforming to the protocol.
Returning dynamic Shape to some Shape is not valid. However, we can make our own ShapeBuilder, the same way ViewBuilder does.
ViewBuilder under the hood
The convenient SwiftUI syntax we have is powered via ViewBuilder, so in a sense we can use ViewBuilder function directly, or declare explicitly with the underlying type like TupleView.