swiftui-conventions
SwiftUI conventions for Apple apps: app and scene structure, view composition and identity, modifiers and custom ViewModifiers, layout (stacks, Grid, ViewThatFits, Layout), lists and lazy containers,
Files1
View on GitHubSKILL.mdplugins/apple-plugin/skills/swiftui-conventions/SKILL.md
GitHubSwiftUI Conventions
App and scene structure
@main
struct OrdersApp: App {
@State private var session = SessionModel()
let container: ModelContainer = .shared
var body: some Scene {
WindowGroup {
RootView()
.environment(session)
}
.modelContainer(container)
}
}
- Long-lived services and app-wide models are created once at the app (or scene) level and injected through the environment — never created inside a view's
body. - A UIKit-lifecycle app (
AppDelegate/SceneDelegate) hosts SwiftUI screens throughUIHostingController; keep the lifecycle it has.
Views
- One screen = one file; extract subviews as soon as a
bodystops fitting on a screen or a piece repeats. Prefer smallstructviews over computedsome Viewproperties or@ViewBuilderfunctions for anything with its own state or reuse. - Views are cheap descriptions —
bodymust be pure and fast: no I/O, no formatting of large collections, no object creation that should outlive the render. - Pass views only the data they need (a value or a
@Bindablemodel), not the whole app state. - Stable identity:
ForEachoverIdentifiablemodels or withid:on a real identifier — never\.selfon mutable values or array indices for data that can be reordered. AvoidAnyView; branch withif/switchinside a@ViewBuilderinstead. - Custom styling that repeats becomes a
ViewModifier+Viewextension, or aButtonStyle/LabelStyle— follow what the design system already defines.
Async work
- Start work tied to a view's lifetime in
.task { await model.load() }(cancelled automatically when the view disappears) or.task(id: query) { … }to restart when an input changes. NotonAppear { Task { … } }. - User actions call into the model:
Button("Save") { Task { await model.save() } }— or a synchronous model method that manages its own task when the project does that. - Pull to refresh:
.refreshable { await model.reload() }. - Every screen renders loading, content, empty (
ContentUnavailableView) and error states.
Layout
VStack/HStack/ZStackwith explicitspacingfrom the design tokens;Gridfor aligned rows;LazyVStack/LazyVGridinsideScrollViewfor long content;Listfor system-styled lists with swipe actions and selection.ViewThatFitsand size classes for adaptive layouts — avoidGeometryReaderunless you need the actual size, and never put it at the root of a scrolling container.- Respect safe areas; use
.safeAreaInset/.safeAreaPaddingfor bars instead of manual offsets. - No fixed frames for text containers — text must grow with Dynamic Type.
Visual design
- Colors from the asset catalog (
Color("Brand")or generated symbolsColor.brand) or semantic system colors (.primary,.secondary,Color(.systemBackground)), fonts from text styles (.font(.headline)) or the design system's scaled custom fonts. No hex literals in feature code. - SF Symbols via
Image(systemName:)/Label; check symbol availability against the deployment target. - Follow the system look of the SDK the project builds with (Liquid Glass materials from the 26-series SDKs on): standard controls, toolbars and tab bars adopt it automatically — do not paint opaque custom backgrounds behind system bars, and use
.glassEffect/GlassEffectContainerfor custom floating controls only when the deployment target allows it (if #available). - Dark Mode and increased contrast must work: check new screens in both appearances via previews.
Accessibility
- Every interactive element has a meaningful label:
Label,Button("Title"), or.accessibilityLabel(...)for icon-only buttons. Decorative images:Image(decorative:)or.accessibilityHidden(true). - Group related content with
.accessibilityElement(children: .combine); expose custom actions with.accessibilityAction. .accessibilityIdentifier("orders.list.row")on elements UI tests need — follow the existing naming scheme.- Support Dynamic Type up to accessibility sizes: switch
HStacktoVStackwith@Environment(\.dynamicTypeSize)when content no longer fits. - Respect Reduce Motion (
@Environment(\.accessibilityReduceMotion)) for non-essential animation.
Localization
- String Catalog (
Localizable.xcstrings):Text("orders.empty.title")/String(localized: "orders.empty.title")with a key or the English source string — match the project's convention. Add a comment for translators where the meaning is ambiguous. - Pluralization through the catalog's plural variants, not string concatenation. Format numbers, dates, currency and measurements with
.formatted()/FormatStyle, never by hand.
Environment
- Custom environment values with the
@Entrymacro:
extension EnvironmentValues {
@Entry var analytics: any AnalyticsClient = NoopAnalyticsClient()
}
- Read with
@Environment(\.analytics); observable models with@Environment(SessionModel.self).
Previews
- Every new screen and reusable component has a
#Previewwith representative states (content, empty, error, long text). Use@Previewable @Statefor interactive previews and in-memory data (ModelContainerin memory, stub services). - Previews must compile — they are part of the build.
UIKit / AppKit interop
UIViewRepresentable/UIViewControllerRepresentable(NSViewRepresentableon Mac) only for what SwiftUI lacks; keep the coordinator small and forward events to the model.- In a UIKit app, new SwiftUI screens live in
UIHostingControllersubclasses or factory functions — follow the existing pattern.
Performance
- Keep observable state granular so a change re-renders only the views that read it (see swiftui-state).
- Images:
AsyncImagefor simple cases, or the project's image loader; downsample large images before display. - Heavy work (parsing, image processing) off the main actor — a
@concurrent/nonisolatedasync function or an actor — then assign results on the main actor. - Use
Self._printChanges()/ Instruments' SwiftUI template to diagnose redundant updates; never leave_printChangesin committed code.