Member-only story
16 Useful Extensions for SwiftUI
Some useful code snippets I repeatedly use in projects
As we get closer to WWDC 2022 and possibly version 4.0 of SwiftUI, a framework I've been lucky to have played with almost as long as it’s been around, I thought I might publish a small collection of extensions I find myself using again and again. I hope some of these make it into the next release.
1. Hide
This is a view modifier that lets you show or hide views that you usually might not be able to. It’s worth mentioning that a view modifier is a super helpful pattern you’d do well to commit to memory.
This you use simply as a modifier on your view, the condition variable is simply a bool.
.modifier(Show(isVisible: condition))
This works well, but as you’ll notice, it does free up space on the view
and forces a redraw — so a performance hit. Alternatively, you can also always use the opacity
tab to get a similar effect. It will run faster but will not free up the space you used.
2. Branch
This modifier I came across is a perfect solution to control attributes inclusion/exclusion.
extension View {
@ViewBuilder
func `if`<Transform: View>(_ condition: Bool, transform: (Self) -> Transform) -> some View {
if condition { transform(self) }
else { self }
}
}
Code you use like this, again with a variable in there, coloured in this example.
.if(colored) { view in
view.background(Color.blue)
}
3. Print
If you are new to SwiftUI, one of the first things that will catch you out is print
. It may be the dinosaur of debugging techniques, but they’re still teaching it in classes, and finding yourself unable to use it in SwiftUI views is painful. So, this code snippet is invaluable.
extension View {
func Print(_ vars: Any...) -> some View {
for v in vars {…