swiftui-patterns-developer
Standardizes SwiftUI view structure and file organization. Helps developers refactor large views into manageable components.
Install
mkdir -p .claude/skills/swiftui-patterns-developer && curl -L -o skill.zip "https://agentskills.codes/api/skills/download/6716" && unzip -o skill.zip -d .claude/skills/swiftui-patterns-developer && rm skill.zipInstalls to .claude/skills/swiftui-patterns-developer
Activation
This is the description your AI agent reads to decide when to run this skill — the better it matches your request, the more reliably it fires.
SwiftUI view structure, composition, and best practices. Use when refactoring SwiftUI views, organizing view files, or extracting subviews.Key capabilities
- →Apply consistent structure to SwiftUI views
- →Order properties and methods within SwiftUI structs
- →Extract subviews from larger SwiftUI views
- →Implement the ViewModel pattern for business logic
- →Utilize `@Observable` for state-driven UI updates
- →Integrate SwiftUI views into UIKit applications
How it works
It applies guidelines for view ordering, ViewModel implementation, and observation to structure SwiftUI views. It also provides methods for integrating SwiftUI into UIKit.
Inputs & outputs
When to use swiftui-patterns-developer
- →Splitting a massive view into smaller subviews
- →Organizing SwiftUI view file layout
- →Refactoring view structures for better state management
About this skill
SwiftUI Patterns Developer (Smart Router)
Purpose
Apply consistent structure and patterns to SwiftUI views, with focus on ordering, subview extraction, and proper composition.
When Auto-Activated
- Refactoring SwiftUI view structure
- Organizing view file layout
- Splitting large views into subviews
- Keywords: view structure, view ordering, split view, extract subview, large view, refactor view
Core Guidelines
0) Three Qualities of SwiftUI Views (WWDC24)
Understanding these fundamentals helps you write better SwiftUI code:
1. Declarative - Describe what you want, not how to create it:
// ✅ Declarative - describe the result
List(pets) { pet in
HStack {
Text(pet.name)
Spacer()
Text(pet.species)
}
}
// No need to add/remove rows manually - SwiftUI handles it
2. Compositional - Build complex UIs from simple building blocks:
// ViewBuilder closures define children of containers
HStack { // Container view
Image(...) // Child 1
VStack { // Child 2 (also a container)
Text(...) // Nested child
Text(...) // Nested child
}
Spacer() // Child 3
}
3. State-Driven - UI automatically updates when state changes:
// SwiftUI tracks dependencies and updates views automatically
@State private var count = 0
var body: some View {
Button("Count: \(count)") { // Dependency on `count`
count += 1 // State change triggers re-render
}
}
Key insight: Views are VALUE TYPES (structs), not long-lived objects. They are descriptions of current UI state, not objects that receive commands over time. SwiftUI maintains the actual UI behind the scenes.
1) View Ordering (top -> bottom)
Follow Anytype's property organization from IOS_DEVELOPMENT_GUIDE.md:
struct ExampleView: View {
// 1. Property wrappers (@State, @Injected, @Environment)
@State private var model: ExampleViewModel
@Injected(\.settingsService) private var settingsService
@Environment(\.dismiss) private var dismiss
// 2. Public properties (let/var)
let title: String
// 3. Private properties
private var cancellables = Set<AnyCancellable>()
// 4. Computed properties
private var hasItems: Bool { !model.items.isEmpty }
// 5. init (if needed)
init(title: String) {
self.title = title
_model = State(wrappedValue: ExampleViewModel(title: title))
}
// 6. body
var body: some View {
content
.task { await model.startSubscriptions() }
}
// 7. Computed view builders
private var content: some View { ... }
// 8. Helper / async functions
private func handleTap() { ... }
}
2) ViewModel Pattern (Anytype Standard)
Anytype uses MVVM with ViewModels. Always use ViewModels for business logic:
// View - lightweight, UI only
struct ChatView: View {
@State private var model: ChatViewModel
init(spaceId: String, chatId: String) {
_model = State(wrappedValue: ChatViewModel(spaceId: spaceId, chatId: chatId))
}
var body: some View {
content
.task { await model.startSubscriptions() }
}
private var content: some View {
List(model.messages) { message in
MessageRow(message: message)
}
}
}
// ViewModel - handles business logic
@MainActor
@Observable
final class ChatViewModel {
var messages: [Message] = []
@ObservationIgnored
@Injected(\.chatService) private var chatService
func startSubscriptions() async {
// Heavy work here, not in init
}
func sendMessage(_ text: String) async {
// Business logic
}
}
Key points:
- Use
@State private var model: ViewModelin views - Initialize ViewModel in view's
initwith_model = State(wrappedValue:) - Keep ViewModel init cheap, heavy work in
.task - Use
@Observablemacro (notObservableObject) - Mark ViewModels with
@MainActor
3) How Observation Works (WWDC23)
Understanding why @Observable works helps you use it correctly.
Property Access Tracking:
- SwiftUI tracks which properties you access during
bodyevaluation - Only those accessed properties trigger view invalidation when changed
- Properties NOT read in
bodydon't cause re-renders (unlike@Published)
@Observable
final class SettingsViewModel {
var userName: String = "" // Accessed in body → triggers update
var isLoading: Bool = false // Accessed in body → triggers update
var analyticsData: Data = Data() // NOT accessed in body → no update
}
struct SettingsView: View {
@State private var model: SettingsViewModel
var body: some View {
// SwiftUI tracks: "this view reads userName and isLoading"
VStack {
Text(model.userName) // ✓ Tracked
if model.isLoading { // ✓ Tracked
ProgressView()
}
// model.analyticsData not read → changes won't invalidate this view
}
}
}
Per-Instance Tracking:
- Arrays of
@Observableobjects work efficiently - Only the specific instance that changed triggers updates
- No need for
identifiabletricks with observation
@Observable
final class MessageViewModel {
var text: String
var isRead: Bool = false
}
// Each MessageRow only updates when ITS message changes
List(model.messages) { message in
MessageRow(message: message) // Only this row updates when message.isRead changes
}
Computed Properties Just Work:
- Computed properties composed from stored properties are automatically tracked
- SwiftUI traces through to the underlying stored properties
@Observable
final class CartViewModel {
var items: [Item] = []
var discount: Double = 0
// Computed → tracks both `items` and `discount`
var totalPrice: Double {
items.reduce(0) { $0 + $1.price } - discount
}
}
Performance Benefit:
With @Observable, views only update when properties they actually read change. This is more efficient than ObservableObject where ANY @Published change triggers objectWillChange for ALL subscribers.
4) Property Wrapper Decision Tree
When to use which wrapper with @Observable:
| Scenario | Wrapper | Why |
|---|---|---|
| View owns model lifecycle | @State | View creates and manages the model |
| Model shared app-wide | @Environment | Injected at app root, read anywhere |
| Just need bindings ($syntax) | @Bindable | Pass to TextField, Toggle, etc. |
| Just reading the model | Nothing | Direct property access triggers tracking |
// View OWNS the model (creates it)
struct ChatView: View {
@State private var model: ChatViewModel // ← @State
init(chatId: String) {
_model = State(wrappedValue: ChatViewModel(chatId: chatId))
}
}
// Model passed from parent, need bindings
struct MessageEditor: View {
@Bindable var draft: DraftMessage // ← @Bindable for $draft.text
var body: some View {
TextField("Message", text: $draft.text)
}
}
// Just reading, no bindings needed
struct MessageRow: View {
let message: MessageViewModel // ← Nothing! Just read properties
var body: some View {
Text(message.text)
Image(systemName: message.isRead ? "checkmark.circle.fill" : "circle")
}
}
Migration from ObservableObject:
| Old | New |
|---|---|
@StateObject | @State |
@ObservedObject | @Bindable or nothing |
@EnvironmentObject | @Environment |
5) Migration from ObservableObject (WWDC23)
Step-by-step conversion from legacy ObservableObject:
Before (ObservableObject):
class SettingsViewModel: ObservableObject {
@Published var userName: String = ""
@Published var notifications: Bool = true
private var cancellables = Set<AnyCancellable>()
}
struct SettingsView: View {
@StateObject private var model = SettingsViewModel()
var body: some View {
TextField("Name", text: $model.userName)
Toggle("Notifications", isOn: $model.notifications)
}
}
After (@Observable):
@Observable
final class SettingsViewModel {
var userName: String = ""
var notifications: Bool = true
@ObservationIgnored
private var cancellables = Set<AnyCancellable>()
}
struct SettingsView: View {
@State private var model = SettingsViewModel()
var body: some View {
@Bindable var model = model // Local binding for $ syntax
TextField("Name", text: $model.userName)
Toggle("Notifications", isOn: $model.notifications)
}
}
Migration Steps:
- Remove
ObservableObjectconformance, add@Observablemacro - Remove
@Publishedfrom all properties (observation is automatic) - Add
@ObservationIgnoredto properties that shouldn't trigger updates - Change
@StateObject→@Statein views - For
$binding syntax, use@Bindable var model = modelin body - Replace
@EnvironmentObjectwith@Environment
Note: Anytype already uses @Observable - this section is for understanding legacy code during migrations.
6) Dependency Injection (Factory)
Anytype uses Factory DI, not SwiftUI Environment for services:
// ✅ CORRECT - Factory DI
@Injected(\.chatService) private var chatService
// ❌ WRONG - Environment for services
@Environment(ChatService.self) private var chatService
Environment is for:
- System values:
@Environment(\.dismiss),@Environment(\.colorScheme) - SwiftUI-provided context
@Injected is for:
- App services:
@Injected(\.chatService) - Repositories:
@Injected(\.userRepository) - Any business logic dependencies
7) View Modifiers and Order (WWDC24)
View modifiers create a hierarchical structure. Order matters - modifiers are applied sequentially:
// Eac
---
*Content truncated.*
When not to use it
- →When using `@Environment` for app services
- →When placing business logic directly in views without a ViewModel
- →When using `Group` with conditionals and lifecycle modifiers
Limitations
- →The skill does not provide full architecture guidance; refer to `IOS_DEVELOPMENT_GUIDE.md` for that.
- →The skill does not cover performance optimization; refer to `swiftui-performance-developer` for that.
- →The skill does not cover design system elements like icons or typography; refer to `design-system-developer` for that.
How it compares
This skill provides specific patterns for SwiftUI view structure and composition, unlike a manual approach that might lack consistency or best practice adherence.
Compared to similar skills
swiftui-patterns-developer side by side with the closest alternatives in the catalog.
| Skill | Installs | Updated | Safety | Difficulty |
|---|---|---|---|---|
| swiftui-patterns-developer (this skill) | 1 | 6mo | No flags | Intermediate |
| swiftui-liquid-glass | 15 | 5mo | No flags | Intermediate |
| mobile-state-management-patterns | 0 | 3mo | No flags | Intermediate |
| gesture-handler-3-migration | 1 | 2mo | No flags | Advanced |
Try saying
Example prompts that trigger this skill in your AI assistant.
More by anyproto
View all by anyproto →You might also like
swiftui-liquid-glass
Dimillian
Implement, review, or improve SwiftUI features using the iOS 26+ Liquid Glass API. Use when asked to adopt Liquid Glass in new SwiftUI UI, refactor an existing feature to Liquid Glass, or review Liquid Glass usage for correctness, performance, and design alignment.
mobile-state-management-patterns
almasumdev
Comparison of mobile state management patterns (MVVM, MVI, TEA, Redux, BLoC, Observable, Compose state, SwiftUI state) and how to choose. Use when designing state flow or evaluating a state library.
gesture-handler-3-migration
software-mansion
Migrates files containing React Native components which use the React Native Gesture Handler 2 API to Gesture Handler 3.
frontend-mobile-development-component-scaffold
sickn33
You are a React component architecture expert specializing in scaffolding production-ready, accessible, and performant components. Generate complete component implementations with TypeScript, tests, s
creating-screens
artsy
Add new screens and routes to Eigen React Native app. Guides you through creating simple screens (no data fetching) or Relay screens (with GraphQL). Use this when adding screens, routes, or navigating components. Triggers on "add a screen", "create a new route", "add a Relay screen", "setup screen with data", or screen creation tasks.
swift-concurrency-6-2
JantonioFC
Swift 6.2 Approachable Concurrency — single-threaded by default, @concurrent