Apple Development Best Practices
Modern Apple platform development using Swift 6 and SwiftUI as primary frameworks.
When to Use
Use this skill when:
- Building iOS or macOS apps with Swift 6 and SwiftUI
- Designing navigation, state management, or concurrency patterns for Apple platforms
- Working with SwiftData, Core Data, StoreKit, CloudKit, or other Apple frameworks
- Reviewing Swift code or planning Apple platform architecture
When NOT to Use
Do NOT use this skill when:
- Building cross-platform mobile apps (Flutter, React Native, Kotlin Multiplatform) — use a cross-platform mobile persona instead, because Apple-specific patterns like
@Observable and NavigationStack don't apply
- Writing server-side Swift (Vapor, Hummingbird) — use a backend engineering persona instead, because server-side Swift has different concurrency, deployment, and architecture concerns
Core Philosophy
Build apps that are previewable, testable, and maintainable. A previewable app is a testable app. A testable app is a maintainable app.
Swift 6 Standards
- Strict concurrency enabled — treat all warnings as errors
@Observable over ObservableObject (iOS 17+)
async/await for all asynchronous operations
- Value types (structs) preferred over reference types (classes) unless identity semantics needed
guard for early exits, never deeply nested if let chains
- Typed errors via
LocalizedError conformance — no raw strings
- No force unwrapping (
!) without documented justification
- Follow Apple's Swift API Design Guidelines for naming
SwiftUI Architecture
State Management — Single Source of Truth (SSOT)
// Local view state → @State
@State private var isExpanded = false
// Observable model → @State with @Observable class
@State private var viewModel = RecipeViewModel()
// Shared across view tree → @Environment
@Environment(\.recipeStore) private var store
// Bindings to @Observable → @Bindable
@Bindable var viewModel: RecipeViewModel
Rules:
@State for view-local state only — never shared across views
@Observable classes for ViewModels (replaces ObservableObject + @Published)
@Environment for dependency injection (services, stores, settings)
- Never pass view models more than 2 levels deep — use Environment instead
Navigation — NavigationStack with Type-Safe Routing
enum Route: Hashable {
case recipeDetail(Recipe)
case settings
case profile(User)
}
@Observable
final class Router {
var path = NavigationPath()
func navigate(to route: Route) {
path.append(route)
}
}
Rules:
NavigationStack only — never deprecated NavigationView
- Type-safe routing via
Hashable enum
- Router as
@Observable class in @Environment
- Sheet presentation via optional ViewModel on parent
View Composition
- Extract subviews at 50+ lines or when reusable
- Max 100 lines per view file before mandatory extraction
- Custom ViewModifiers for shared styling — not repeated inline styles
- Never use
AnyView — destroys diffing performance and identity
- Prefer
@ViewBuilder closures over AnyView for type erasure
Performance
LazyVStack/LazyHStack inside ScrollView — never eager stacks for large lists
EquatableView wrapper for complex views that rarely change
- Keep view body pure — no side effects, no network calls
- Use
.task modifier for async work, not onAppear with Task
- Profile with SwiftUI Performance Instrument (Xcode 16+)
Project Structure
AppName/
├── App/ # App entry, lifecycle, configuration
│ ├── AppNameApp.swift
│ └── AppDelegate.swift # Only if needed for UIKit integration
├── Features/ # Feature modules (self-contained)
│ ├── Recipes/
│ │ ├── Views/ # SwiftUI views
│ │ ├── ViewModels/ # @Observable classes
│ │ └── Models/ # Data models (structs)
│ ├── MealPlanning/
│ └── Community/
├── Core/ # Shared infrastructure
│ ├── Extensions/
│ ├── Services/ # Networking, auth, analytics
│ ├── Persistence/ # SwiftData / Core Data
│ └── Components/ # Reusable UI components
├── Resources/ # Assets, Localizations, Fonts
└── Tests/
├── UnitTests/ # ViewModel + Service tests
└── UITests/ # Critical user flow tests
Rules:
- Features are self-contained — no cross-feature imports
- Shared code lives in
Core/ only
- Each feature has its own Views, ViewModels, Models
- Feature folders mirror navigation structure
Concurrency
// Actor for thread-safe shared state
actor RecipeStore {
private var cache: [UUID: Recipe] = [:]
func recipe(for id: UUID) -> Recipe? {
cache[id]
}
}
// @MainActor for UI-bound classes
@MainActor
@Observable
final class RecipeListViewModel {
var recipes: [Recipe] = []
var isLoading = false
func loadRecipes() async {
isLoading = true
defer { isLoading = false }
recipes = await recipeService.fetchAll()
}
}
Rules:
@MainActor on all ViewModels
actor for shared mutable state
Sendable conformance for types crossing isolation boundaries
- Never
DispatchQueue.main.async — use @MainActor instead
Task only inside .task modifier or explicit user-initiated actions
TaskGroup for parallel independent work
Testing
- Swift Testing (
@Test, #expect) preferred over XCTest for new code
- Unit tests for all ViewModel logic — 80%+ coverage on business logic
- UI tests for critical user flows only (login, purchase, core CRUD)
- Dependency injection via protocols for testability
- No singletons in production code — inject via
@Environment
- Preview-driven development: if a view is hard to preview, it's hard to test
Persistence
SwiftData (iOS 17+) is the default persistence layer:
@Model
final class Recipe {
var name: String
var ingredients: [String]
var instructions: String
@Relationship(deleteRule: .cascade)
var steps: [CookingStep]
}
Rules:
@Model classes for SwiftData — not structs
- Define
@Relationship explicitly with delete rules
- Use
@Query in views for automatic updates
- ModelContainer configured in App entry point
- Migration strategy documented before schema changes
Networking
protocol RecipeServiceProtocol: Sendable {
func fetchAll() async throws -> [Recipe]
func create(_ recipe: Recipe) async throws -> Recipe
}
struct RecipeService: RecipeServiceProtocol {
private let session: URLSession
private let decoder: JSONDecoder
func fetchAll() async throws -> [Recipe] {
let (data, response) = try await session.data(from: endpoint)
guard let http = response as? HTTPURLResponse,
(200...299).contains(http.statusCode) else {
throw AppError.networkError(statusCode: http.statusCode)
}
return try decoder.decode([Recipe].self, from: data)
}
}
Rules:
- Protocol-based services for testability
Sendable conformance on all service types
- Typed errors with
LocalizedError
- No third-party HTTP libraries unless justified (URLSession is sufficient)
- Certificate pinning for sensitive data
Security
- Keychain for credentials, tokens, secrets — never UserDefaults
- App Transport Security enabled — HTTPS only
- No sensitive data in logs or crash reports
@AppStorage only for non-sensitive user preferences
- Input validation on all user-provided data
- Privacy manifest (
PrivacyInfo.xcprivacy) for App Store compliance
Accessibility
- Every interactive element needs an
accessibilityLabel
- Use semantic SwiftUI elements (Button, Toggle, Picker) — not
.onTapGesture
- Support Dynamic Type — no hardcoded font sizes
- Minimum tap target 44x44pt
- Test with VoiceOver before shipping
Deep References
See references/ for detailed guidance:
references/swiftui-patterns.md — Advanced view patterns, custom layouts, animations
references/concurrency-guide.md — Actor isolation, Sendable, structured concurrency
references/xcode-claude-integration.md — XcodeBuildMCP setup, hooks, sandbox modes
references/migration-guide.md — UIKit → SwiftUI, CoreData → SwiftData paths
1---2name: apple-dev-best-practices3version: "2.0.0"4lifecycle: experimental5type: persona6category: domain7risk_level: low8description: Apple platform development best practices for Swift 6, SwiftUI, SwiftData, and iOS/macOS apps. Use when building any iOS or macOS app, writing Swift code, designing SwiftUI views, working with Xcode projects, implementing navigation, state management, concurrency, networking, persistence, or testing on Apple platforms. Triggers on Swift, SwiftUI, iOS, macOS, Xcode, UIKit, SwiftData, Core Data, XCTest, StoreKit, CloudKit, MapKit, HealthKit, or any Apple framework. Also use when reviewing Swift code, debugging iOS apps, migrating UIKit to SwiftUI, or planning Apple platform architecture.9metadata: {"openclaw": {"emoji": "📱", "os": ["darwin", "linux", "win32"]}}10user-invocable: true11---1213# Apple Development Best Practices1415Modern Apple platform development using Swift 6 and SwiftUI as primary frameworks.1617## When to Use1819Use this skill when:20- Building iOS or macOS apps with Swift 6 and SwiftUI21- Designing navigation, state management, or concurrency patterns for Apple platforms22- Working with SwiftData, Core Data, StoreKit, CloudKit, or other Apple frameworks23- Reviewing Swift code or planning Apple platform architecture2425## When NOT to Use2627Do NOT use this skill when:28- Building cross-platform mobile apps (Flutter, React Native, Kotlin Multiplatform) — use a cross-platform mobile persona instead, because Apple-specific patterns like `@Observable` and `NavigationStack` don't apply29- Writing server-side Swift (Vapor, Hummingbird) — use a backend engineering persona instead, because server-side Swift has different concurrency, deployment, and architecture concerns3031## Core Philosophy3233Build apps that are **previewable, testable, and maintainable**. A previewable app is a testable app. A testable app is a maintainable app.3435## Swift 6 Standards3637- **Strict concurrency** enabled — treat all warnings as errors38- **`@Observable`** over `ObservableObject` (iOS 17+)39- **`async/await`** for all asynchronous operations40- **Value types** (structs) preferred over reference types (classes) unless identity semantics needed41- **`guard`** for early exits, never deeply nested `if let` chains42- **Typed errors** via `LocalizedError` conformance — no raw strings43- **No force unwrapping** (`!`) without documented justification44- Follow Apple's Swift API Design Guidelines for naming4546## SwiftUI Architecture4748### State Management — Single Source of Truth (SSOT)4950```swift51// Local view state → @State52@State private var isExpanded = false5354// Observable model → @State with @Observable class55@State private var viewModel = RecipeViewModel()5657// Shared across view tree → @Environment58@Environment(\.recipeStore) private var store5960// Bindings to @Observable → @Bindable61@Bindable var viewModel: RecipeViewModel62```6364**Rules:**65- `@State` for view-local state only — never shared across views66- `@Observable` classes for ViewModels (replaces `ObservableObject` + `@Published`)67- `@Environment` for dependency injection (services, stores, settings)68- Never pass view models more than 2 levels deep — use Environment instead6970### Navigation — NavigationStack with Type-Safe Routing7172```swift73enum Route: Hashable {74 case recipeDetail(Recipe)75 case settings76 case profile(User)77}7879@Observable80final class Router {81 var path = NavigationPath()8283 func navigate(to route: Route) {84 path.append(route)85 }86}87```8889**Rules:**90- `NavigationStack` only — never deprecated `NavigationView`91- Type-safe routing via `Hashable` enum92- Router as `@Observable` class in `@Environment`93- Sheet presentation via optional ViewModel on parent9495### View Composition9697- Extract subviews at **50+ lines** or when reusable98- Max **100 lines** per view file before mandatory extraction99- Custom ViewModifiers for shared styling — not repeated inline styles100- Never use `AnyView` — destroys diffing performance and identity101- Prefer `@ViewBuilder` closures over `AnyView` for type erasure102103### Performance104105- **`LazyVStack`/`LazyHStack`** inside ScrollView — never eager stacks for large lists106- **`EquatableView`** wrapper for complex views that rarely change107- Keep view body **pure** — no side effects, no network calls108- Use `.task` modifier for async work, not `onAppear` with Task109- Profile with SwiftUI Performance Instrument (Xcode 16+)110111## Project Structure112113```114AppName/115├── App/ # App entry, lifecycle, configuration116│ ├── AppNameApp.swift117│ └── AppDelegate.swift # Only if needed for UIKit integration118├── Features/ # Feature modules (self-contained)119│ ├── Recipes/120│ │ ├── Views/ # SwiftUI views121│ │ ├── ViewModels/ # @Observable classes122│ │ └── Models/ # Data models (structs)123│ ├── MealPlanning/124│ └── Community/125├── Core/ # Shared infrastructure126│ ├── Extensions/127│ ├── Services/ # Networking, auth, analytics128│ ├── Persistence/ # SwiftData / Core Data129│ └── Components/ # Reusable UI components130├── Resources/ # Assets, Localizations, Fonts131└── Tests/132 ├── UnitTests/ # ViewModel + Service tests133 └── UITests/ # Critical user flow tests134```135136**Rules:**137- Features are **self-contained** — no cross-feature imports138- Shared code lives in `Core/` only139- Each feature has its own Views, ViewModels, Models140- Feature folders mirror navigation structure141142## Concurrency143144```swift145// Actor for thread-safe shared state146actor RecipeStore {147 private var cache: [UUID: Recipe] = [:]148149 func recipe(for id: UUID) -> Recipe? {150 cache[id]151 }152}153154// @MainActor for UI-bound classes155@MainActor156@Observable157final class RecipeListViewModel {158 var recipes: [Recipe] = []159 var isLoading = false160161 func loadRecipes() async {162 isLoading = true163 defer { isLoading = false }164 recipes = await recipeService.fetchAll()165 }166}167```168169**Rules:**170- `@MainActor` on all ViewModels171- `actor` for shared mutable state172- `Sendable` conformance for types crossing isolation boundaries173- Never `DispatchQueue.main.async` — use `@MainActor` instead174- `Task` only inside `.task` modifier or explicit user-initiated actions175- `TaskGroup` for parallel independent work176177## Testing178179- **Swift Testing** (`@Test`, `#expect`) preferred over XCTest for new code180- **Unit tests** for all ViewModel logic — 80%+ coverage on business logic181- **UI tests** for critical user flows only (login, purchase, core CRUD)182- **Dependency injection** via protocols for testability183- **No singletons** in production code — inject via `@Environment`184- Preview-driven development: if a view is hard to preview, it's hard to test185186## Persistence187188**SwiftData** (iOS 17+) is the default persistence layer:189190```swift191@Model192final class Recipe {193 var name: String194 var ingredients: [String]195 var instructions: String196 @Relationship(deleteRule: .cascade)197 var steps: [CookingStep]198}199```200201**Rules:**202- `@Model` classes for SwiftData — not structs203- Define `@Relationship` explicitly with delete rules204- Use `@Query` in views for automatic updates205- ModelContainer configured in App entry point206- Migration strategy documented before schema changes207208## Networking209210```swift211protocol RecipeServiceProtocol: Sendable {212 func fetchAll() async throws -> [Recipe]213 func create(_ recipe: Recipe) async throws -> Recipe214}215216struct RecipeService: RecipeServiceProtocol {217 private let session: URLSession218 private let decoder: JSONDecoder219220 func fetchAll() async throws -> [Recipe] {221 let (data, response) = try await session.data(from: endpoint)222 guard let http = response as? HTTPURLResponse,223 (200...299).contains(http.statusCode) else {224 throw AppError.networkError(statusCode: http.statusCode)225 }226 return try decoder.decode([Recipe].self, from: data)227 }228}229```230231**Rules:**232- Protocol-based services for testability233- `Sendable` conformance on all service types234- Typed errors with `LocalizedError`235- No third-party HTTP libraries unless justified (URLSession is sufficient)236- Certificate pinning for sensitive data237238## Security239240- **Keychain** for credentials, tokens, secrets — never UserDefaults241- **App Transport Security** enabled — HTTPS only242- No sensitive data in logs or crash reports243- `@AppStorage` only for non-sensitive user preferences244- Input validation on all user-provided data245- Privacy manifest (`PrivacyInfo.xcprivacy`) for App Store compliance246247## Accessibility248249- Every interactive element needs an `accessibilityLabel`250- Use semantic SwiftUI elements (Button, Toggle, Picker) — not `.onTapGesture`251- Support Dynamic Type — no hardcoded font sizes252- Minimum tap target 44x44pt253- Test with VoiceOver before shipping254255## Deep References256257See `references/` for detailed guidance:258- `references/swiftui-patterns.md` — Advanced view patterns, custom layouts, animations259- `references/concurrency-guide.md` — Actor isolation, Sendable, structured concurrency260- `references/xcode-claude-integration.md` — XcodeBuildMCP setup, hooks, sandbox modes261- `references/migration-guide.md` — UIKit → SwiftUI, CoreData → SwiftData paths