Skill: Swift Code Writer
Description
Generates production-quality Swift code following modern best practices and idioms for iOS/macOS development. Focuses on structured concurrency, the Observation framework, SwiftUI's declarative patterns, and SwiftData for persistence. Targets iOS 19+ and macOS 16+.
When to Use This Skill
Use this skill when:
- Writing Swift code for experienced developers
- Focus is on correct, idiomatic implementation over teaching
- Modern Swift patterns and best practices must be followed
- Building SwiftUI applications with SwiftData
- Code needs to work across iOS, iPadOS, and macOS
Instructions
Target Specifications
- Platform Targets: iOS 19+, macOS 16+, iPadOS 19+
- Swift Version: Latest available in Xcode
- Primary Frameworks: SwiftUI, SwiftData
- Concurrency Model: Structured concurrency (
async/await, Actors)
Modern Swift Patterns (Required)
Concurrency
- Default to
async/await for all asynchronous operations
- Use structured concurrency primitives:
Task for launching async work
async let for parallel async operations
- Task Groups for dynamic parallel operations
- Actors for managing concurrent mutable state
- Use modern
async-aware system APIs (e.g., URLSession.shared.data(from:))
Observation
- Use
@Observable macro for all view models and observable objects
- Leverages Swift's Observation framework (replaces
@ObservableObject)
Type System
- Leverage Swift's strong type system: protocols, generics, optionals
- Use value types (structs) by default; reference types (classes with
@Observable) when needed
- Make type decisions based on semantics and performance requirements
Legacy Patterns (Prohibited)
Do NOT use these patterns unless absolutely required for interoperability:
- Completion Handlers/Delegates: Refactor to
async/await
- NotificationCenter for State: Use
@Environment, observable objects, or dependency injection
- Combine Framework: Prefer
async/await and @Observable (only use if specific API requires it)
- UIKit/AppKit: Avoid
UIViewRepresentable/NSViewRepresentable (use only if no SwiftUI equivalent exists)
- Core Data: Use SwiftData instead (only use Core Data for legacy database migration)
SwiftUI Guidelines
Multi-Platform Design
- Design features to work idiomatically on macOS, iOS, and iPadOS
- Respect platform conventions:
- Sidebar navigation on macOS and iPadOS
- Appropriate context menus
- Platform-appropriate control sizing
- Use adaptive layouts for different screen sizes and input methods (touch, mouse, trackpad)
- Use compile-time platform checks when needed:
#if os(iOS), #if os(macOS)
Idiomatic SwiftUI
- Prefer semantic SwiftUI elements:
LabeledContent, Toggle, Picker, Slider
- These provide accessibility, proper layout, and platform behaviors automatically
- Compose views into small, reusable components
- Use proper data flow:
@State, @Binding, @Environment, @Bindable
- Use
NavigationStack for navigation management
- Use
.task for async work on view lifecycle (preferred over .onAppear for async operations)
SwiftData Usage
- Use
@Model macro for data models
- Use
ModelContext for persistence operations
- Use
#Predicate for type-safe queries
- Define relationships between models clearly
- SwiftData is the default for local persistence
Package Management
- Only import Swift Packages when necessary
- Prefer official Apple packages when available
- Use widely-used, well-maintained community packages
- Ensure packages align with modern Swift tech stack
- Confirm major package additions with project requirements
Code Quality Standards
Testing
- Write unit tests using XCTest for:
- Models and data layer
- View models and business logic
- Critical application paths
- Tests should cover expected behavior and edge cases
- Use Xcode's UI Testing framework for UI tests when needed
Error Handling
- Use Swift's
Error protocol for error types
- Handle errors with
do-try-catch blocks
- Use
Result type when appropriate
- Propagate and handle errors gracefully in
async contexts
- Display error states clearly in SwiftUI views
Comments
- Document purpose, logic, and rationale (not "what" but "why")
- Explain use of specific Swift features when non-obvious:
- Why
@Observable is appropriate here
- Why this specific
async pattern
- Complex generics or type constraints
- Non-obvious SwiftUI modifiers or SwiftData queries
- Prefer single-line comments (
//) over block comments
- Use underscore (
_) for intentionally unused parameters
Code Organization
View Complexity
- Refactor complex views into smaller, reusable subviews
- Keep view bodies focused and readable
- Extract repeated UI patterns into custom views
State Management
- For simple local state:
@State
- For shared state across views: Create
@Observable class and inject via .environment()
- For complex navigation: Use
NavigationPath with NavigationStack
Readability & Maintainability
- Prioritize code clarity
- Use Swift's declarative patterns for UI and data flow
- Minimize imperative code
- Leverage SwiftUI's declarative nature
Staying Current
Before generating code:
- Use search tools to verify current best practices for Swift/SwiftUI/SwiftData patterns
- Check for recent framework changes or deprecations in latest iOS/macOS releases
- Confirm API availability for target platform versions
- If discovering updated patterns or approaches, note for skill updates
- Suggest updating this skill or swift-mentor skill when significant changes are found
Examples
Example 1: Async Data Fetching with Error Handling
@Observable
class ArticleViewModel {
var articles: [Article] = []
var isLoading = false
var error: Error?
func fetchArticles() async {
isLoading = true
defer { isLoading = false }
do {
let (data, _) = try await URLSession.shared.data(from: articlesURL)
articles = try JSONDecoder().decode([Article].self, from: data)
error = nil
} catch {
self.error = error
articles = []
}
}
}
struct ArticlesView: View {
@State private var viewModel = ArticleViewModel()
var body: some View {
List(viewModel.articles) { article in
ArticleRow(article: article)
}
.overlay {
if viewModel.isLoading {
ProgressView()
}
}
.alert("Error", isPresented: .constant(viewModel.error != nil)) {
Button("OK") { viewModel.error = nil }
} message: {
Text(viewModel.error?.localizedDescription ?? "")
}
.task {
await viewModel.fetchArticles()
}
}
}
Example 2: SwiftData Model with Relationships
import SwiftData
@Model
final class Project {
var name: String
var createdAt: Date
@Relationship(deleteRule: .cascade) var tasks: [Task]
init(name: String, createdAt: Date = .now) {
self.name = name
self.createdAt = createdAt
self.tasks = []
}
}
@Model
final class Task {
var title: String
var isCompleted: Bool
var project: Project?
init(title: String, isCompleted: Bool = false) {
self.title = title
self.isCompleted = isCompleted
}
}
Example 3: Multi-Platform Adaptive Layout
struct SidebarView: View {
var body: some View {
#if os(macOS)
List {
NavigationLink("Home", destination: HomeView())
NavigationLink("Settings", destination: SettingsView())
}
.navigationTitle("Menu")
#else
List {
NavigationLink(destination: HomeView()) {
Label("Home", systemImage: "house")
}
NavigationLink(destination: SettingsView()) {
Label("Settings", systemImage: "gear")
}
}
.navigationTitle("Menu")
.navigationBarTitleDisplayMode(.inline)
#endif
}
}
Prerequisites
- Xcode (latest version)
- Swift development environment
- Understanding of Swift fundamentals
Notes
This skill focuses on code generation following modern Swift best practices without extensive explanations. For teaching or mentoring scenarios where concepts need explanation, use the swift-mentor skill instead.
Key principles:
- Modern patterns only (no legacy approaches)
- Idiomatic Swift code
- SwiftUI-first for UI
- SwiftData-first for persistence
- Structured concurrency for async operations
- Multi-platform awareness
Converted and distributed by TomeVault — claim your Tome and manage your conversions.
1---2name: swift-code-writer3description: Generates idiomatic Swift code using modern patterns (async/await, Observation, SwiftUI, SwiftData) for iOS/macOS. Use when writing Swift code, building iOS/macOS apps, or when user needs Swift implementation.4---56# Skill: Swift Code Writer78## Description910Generates production-quality Swift code following modern best practices and idioms for iOS/macOS development. Focuses on structured concurrency, the Observation framework, SwiftUI's declarative patterns, and SwiftData for persistence. Targets iOS 19+ and macOS 16+.1112## When to Use This Skill1314Use this skill when:15- Writing Swift code for experienced developers16- Focus is on correct, idiomatic implementation over teaching17- Modern Swift patterns and best practices must be followed18- Building SwiftUI applications with SwiftData19- Code needs to work across iOS, iPadOS, and macOS2021## Instructions2223### Target Specifications2425- **Platform Targets**: iOS 19+, macOS 16+, iPadOS 19+26- **Swift Version**: Latest available in Xcode27- **Primary Frameworks**: SwiftUI, SwiftData28- **Concurrency Model**: Structured concurrency (`async/await`, Actors)2930### Modern Swift Patterns (Required)3132#### Concurrency33- Default to `async/await` for all asynchronous operations34- Use structured concurrency primitives:35 - `Task` for launching async work36 - `async let` for parallel async operations37 - Task Groups for dynamic parallel operations38 - Actors for managing concurrent mutable state39- Use modern `async`-aware system APIs (e.g., `URLSession.shared.data(from:)`)4041#### Observation42- Use `@Observable` macro for all view models and observable objects43- Leverages Swift's Observation framework (replaces `@ObservableObject`)4445#### Type System46- Leverage Swift's strong type system: protocols, generics, optionals47- Use value types (structs) by default; reference types (classes with `@Observable`) when needed48- Make type decisions based on semantics and performance requirements4950### Legacy Patterns (Prohibited)5152Do NOT use these patterns unless absolutely required for interoperability:5354- **Completion Handlers/Delegates**: Refactor to `async/await`55- **NotificationCenter for State**: Use `@Environment`, observable objects, or dependency injection56- **Combine Framework**: Prefer `async/await` and `@Observable` (only use if specific API requires it)57- **UIKit/AppKit**: Avoid `UIViewRepresentable`/`NSViewRepresentable` (use only if no SwiftUI equivalent exists)58- **Core Data**: Use SwiftData instead (only use Core Data for legacy database migration)5960### SwiftUI Guidelines6162#### Multi-Platform Design63- Design features to work idiomatically on macOS, iOS, and iPadOS64- Respect platform conventions:65 - Sidebar navigation on macOS and iPadOS66 - Appropriate context menus67 - Platform-appropriate control sizing68- Use adaptive layouts for different screen sizes and input methods (touch, mouse, trackpad)69- Use compile-time platform checks when needed: `#if os(iOS)`, `#if os(macOS)`7071#### Idiomatic SwiftUI72- Prefer semantic SwiftUI elements: `LabeledContent`, `Toggle`, `Picker`, `Slider`73- These provide accessibility, proper layout, and platform behaviors automatically74- Compose views into small, reusable components75- Use proper data flow: `@State`, `@Binding`, `@Environment`, `@Bindable`76- Use `NavigationStack` for navigation management77- Use `.task` for async work on view lifecycle (preferred over `.onAppear` for async operations)7879### SwiftData Usage8081- Use `@Model` macro for data models82- Use `ModelContext` for persistence operations83- Use `#Predicate` for type-safe queries84- Define relationships between models clearly85- SwiftData is the default for local persistence8687### Package Management8889- Only import Swift Packages when necessary90- Prefer official Apple packages when available91- Use widely-used, well-maintained community packages92- Ensure packages align with modern Swift tech stack93- Confirm major package additions with project requirements9495### Code Quality Standards9697#### Testing98- Write unit tests using XCTest for:99 - Models and data layer100 - View models and business logic101 - Critical application paths102- Tests should cover expected behavior and edge cases103- Use Xcode's UI Testing framework for UI tests when needed104105#### Error Handling106- Use Swift's `Error` protocol for error types107- Handle errors with `do-try-catch` blocks108- Use `Result` type when appropriate109- Propagate and handle errors gracefully in `async` contexts110- Display error states clearly in SwiftUI views111112#### Comments113- Document purpose, logic, and rationale (not "what" but "why")114- Explain use of specific Swift features when non-obvious:115 - Why `@Observable` is appropriate here116 - Why this specific `async` pattern117 - Complex generics or type constraints118 - Non-obvious SwiftUI modifiers or SwiftData queries119- Prefer single-line comments (`//`) over block comments120- Use underscore (`_`) for intentionally unused parameters121122### Code Organization123124#### View Complexity125- Refactor complex views into smaller, reusable subviews126- Keep view bodies focused and readable127- Extract repeated UI patterns into custom views128129#### State Management130- For simple local state: `@State`131- For shared state across views: Create `@Observable` class and inject via `.environment()`132- For complex navigation: Use `NavigationPath` with `NavigationStack`133134#### Readability & Maintainability135- Prioritize code clarity136- Use Swift's declarative patterns for UI and data flow137- Minimize imperative code138- Leverage SwiftUI's declarative nature139140### Staying Current141142Before generating code:143- Use search tools to verify current best practices for Swift/SwiftUI/SwiftData patterns144- Check for recent framework changes or deprecations in latest iOS/macOS releases145- Confirm API availability for target platform versions146- If discovering updated patterns or approaches, note for skill updates147- Suggest updating this skill or swift-mentor skill when significant changes are found148149## Examples150151### Example 1: Async Data Fetching with Error Handling152153```swift154@Observable155class ArticleViewModel {156 var articles: [Article] = []157 var isLoading = false158 var error: Error?159 160 func fetchArticles() async {161 isLoading = true162 defer { isLoading = false }163 164 do {165 let (data, _) = try await URLSession.shared.data(from: articlesURL)166 articles = try JSONDecoder().decode([Article].self, from: data)167 error = nil168 } catch {169 self.error = error170 articles = []171 }172 }173}174175struct ArticlesView: View {176 @State private var viewModel = ArticleViewModel()177 178 var body: some View {179 List(viewModel.articles) { article in180 ArticleRow(article: article)181 }182 .overlay {183 if viewModel.isLoading {184 ProgressView()185 }186 }187 .alert("Error", isPresented: .constant(viewModel.error != nil)) {188 Button("OK") { viewModel.error = nil }189 } message: {190 Text(viewModel.error?.localizedDescription ?? "")191 }192 .task {193 await viewModel.fetchArticles()194 }195 }196}197```198199### Example 2: SwiftData Model with Relationships200201```swift202import SwiftData203204@Model205final class Project {206 var name: String207 var createdAt: Date208 @Relationship(deleteRule: .cascade) var tasks: [Task]209 210 init(name: String, createdAt: Date = .now) {211 self.name = name212 self.createdAt = createdAt213 self.tasks = []214 }215}216217@Model218final class Task {219 var title: String220 var isCompleted: Bool221 var project: Project?222 223 init(title: String, isCompleted: Bool = false) {224 self.title = title225 self.isCompleted = isCompleted226 }227}228```229230### Example 3: Multi-Platform Adaptive Layout231232```swift233struct SidebarView: View {234 var body: some View {235 #if os(macOS)236 List {237 NavigationLink("Home", destination: HomeView())238 NavigationLink("Settings", destination: SettingsView())239 }240 .navigationTitle("Menu")241 #else242 List {243 NavigationLink(destination: HomeView()) {244 Label("Home", systemImage: "house")245 }246 NavigationLink(destination: SettingsView()) {247 Label("Settings", systemImage: "gear")248 }249 }250 .navigationTitle("Menu")251 .navigationBarTitleDisplayMode(.inline)252 #endif253 }254}255```256257## Prerequisites258259- Xcode (latest version)260- Swift development environment261- Understanding of Swift fundamentals262263## Notes264265This skill focuses on code generation following modern Swift best practices without extensive explanations. For teaching or mentoring scenarios where concepts need explanation, use the `swift-mentor` skill instead.266267Key principles:268- Modern patterns only (no legacy approaches)269- Idiomatic Swift code270- SwiftUI-first for UI271- SwiftData-first for persistence272- Structured concurrency for async operations273- Multi-platform awareness274275---276> Converted and distributed by [TomeVault](https://tomevault.io/claim/jd-santos) — claim your Tome and manage your conversions.277<!-- tomevault:4.0:skill_md:2026-04-16 -->