Swift/SwiftUI Best Practices
SwiftUI View Composition
- Break views into small, single-responsibility components; extract reusable pieces into
Viewstructs - Use
@ViewBuilderfor conditional and grouped content; prefer composition over deep nesting - Apply modifiers consistently -- chain them in a logical order: layout -> appearance -> accessibility
- Use
ViewModifierprotocol for reusable modifier groups shared across views - Keep view bodies free of business logic; move computation to ViewModels or use computed properties on the model
Swift Concurrency
- Use
async/awaitas the primary concurrency model; avoid completion handlers in new code - Adopt
Actorfor shared mutable state isolation:actor DataStore { ... } - Use
TaskGroupfor structured concurrency when spawning dynamic child tasks - Apply
.taskmodifier in SwiftUI for view-scoped async work that cancels on disappear - Use
Sendableconformance to guarantee thread-safe value types across concurrency boundaries
SwiftData
- Define models with
@Modelmacro; use@Relationshipfor references and@Attributefor constraints - Use
ModelContainerto configure storage: in-memory for previews, persistent for production - Query with
@Queryin SwiftUI views; apply#Predicatefor type-safe filtering and sorting - Keep model types simple -- derive computed properties for presentation logic rather than storing derived data
- Use
ModelContextdirectly in ViewModels for batch inserts, deletes, and background saves
UIKit Interop
- Use
UIViewControllerRepresentableandUIViewRepresentableto wrap UIKit components in SwiftUI - Delegate pattern: implement the delegate protocol in a coordinator class nested inside the representable
- Use
UIHostingControllerto embed SwiftUI views within UIKit navigation flows - Prefer SwiftUI-native solutions before falling back to UIKit; only interop when no SwiftUI equivalent exists
visionOS Spatial Computing
- Use
RealityViewfor 3D content andImmersiveSpacefor full-room experiences - Apply
Volumefor bounded 3D windows andWindowfor traditional 2D-style panels - Use ARKit skeleton tracking and hand tracking via
HandTrackingProviderfor spatial input - Design for comfort: keep content at comfortable distances, avoid rapid depth changes, provide rest states
- Test spatial UI in the visionOS simulator with varied room layouts before device testing
Testing and Quality
- Use Swift Testing framework (
@Test,@Suite) for new test targets alongside XCTest for compatibility - Write
PreviewProvideror#Previewmacros for every SwiftUI view to enable live canvas development - Apply SwiftLint or SwiftFormat consistently; enforce rules in CI with
swift-format - Use Instruments for profiling: Time Profiler, Allocations, and Leaks for performance validation
Source: calcosmic/Aether — distributed by TomeVault.