Swizzling SwiftUI View Body
Article Summary
Noah Martin from Sentry cracked a problem that seemed impossible: swizzling pure Swift code to automatically track SwiftUI view performance. The technique is wild.
UIKit apps get automatic performance tracing through Objective-C swizzling, but SwiftUI's pure Swift types don't support this. Martin details how Sentry's ViewPerformance package achieves similar functionality by parsing protocol conformance descriptors and using software breakpoints to hook into every SwiftUI view body.
Key Takeaways
- Protocol conformance descriptors reveal all types conforming to SwiftUI.View at runtime
- Software breakpoints intercept function entry and exit without traditional swizzling
- Works in debug builds only due to executable modification restrictions
- Hardware breakpoints enable TestFlight use but require development mode enabled
- Open source ViewPerformance package available for immediate debug build integration
You can now automatically trace SwiftUI view performance in debug builds using protocol witness tables and breakpoints, bringing UIKit-style automatic instrumentation to pure Swift code.
About This Article
Swift function calls get inlined and optimized away by the compiler, which breaks traditional dyld interposing. The problem is that interposing needs to know which function to hook at compile time.
Noah Martin's team parsed the __swift5_proto binary section to find all protocol conformances. They located the protocol witness table for each SwiftUI.View type, then used dlsym to resolve method descriptors like $s7SwiftUI4ViewP4body4BodyQzvgTq and find where the implementations actually live.
The ViewPerformance package can now automatically instrument every SwiftUI view's body accessor in debug builds without any manual setup. This matches what UIKit already does with automatic tracing, which used to require Objective-C swizzling.