Building SwiftUI Debugging Utilities
In this post, we will explore how to create debugging utilities in SwiftUI to help diagnose and fix issues in your app.
Printing values
As you may know already you cannot use print()
directly in your SwiftUI code.
struct ContentView: View {
var body: some View {
Text("Hello, World!")
let _ = print("This is a debug message") // Print in the supported way
}
}
A way to achieve this functionality is creating a extension on View.
extension View {
func print(_ value: Any) -> Self {
Swift.print(value) // Swift.print to tell Swift that we want to use the native print function
return self
}
}
now we can use:
struct ContentView: View {
var body: some View {
Text("Hello, World!")
.print("This is a debug message")
}
}
Perform custom debugging actions
Sometimes you want to execute code only on the debug build.
One way is:
struct ContentView: View {
var body: some View {
Text("Hello, World!")
#if DEBUG
.print("This is a debug message")
#endif
}
}
A better way to achieve this functionality is creating a extension on View.
extension View {
func debugAction(_ closure: () -> Void) -> Self {
#if DEBUG
closure()
#endif
return self
}
}
now we can use:
struct ContentView: View {
var body: some View {
Text("Hello, World!")
.debugAction {
print("This is a debug message")
}
}
}
Debugging view borders
Sometimes you want to see where the views are located on the screen. You can achieve this by adding borders to your views.
extension View {
func debugBorder(_ color: Color = .red) -> some View {
#if DEBUG
self.border(color, width: 2)
#else
self
#endif
}
}
Now we can use:
struct ContentView: View {
var body: some View {
Text("Hello, World!")
.debugBorder()
}
}
Conclusion
Writing a pair of functions to print debug messages and add borders to views can greatly enhance the debugging experience in SwiftUI. By using conditional compilation and view extensions, we can create a clean and efficient debugging workflow.
Read more
- Simplifying App Onboarding with OnboardingKit • 5 minutes reading time.
- @dynamicMemberLookup • 2 minutes reading time.
- SwiftUI ViewModifiers • 6 minutes reading time.
Share
Share Bluesky Mastodon Twitter LinkedIn Facebook