swiftui-patterns
Skill1 starsChanged 8 months agoMITView on GitHub
SwiftUI architecture patterns, state management with @Observable, view composition, navigation, performance optimization, and modern iOS/macOS UI best practices.
We split this skill into the rules it gives an agent
7 rules. 0 are common, 0 are distinctive, and 7 are very specific to this project.
0
Common
Most of the 8 edited versions we read keep these.
0
Distinctive
This author's own choices. Worth a look.
7
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Very specific: line 35
Use @Observable (not ObservableObject) — it tracks property-level changes so SwiftUI only re-renders views that read the changed property:
- Very specific: line 141
Use NavigationStack with NavigationPath for programmatic, type-safe routing:
- Very specific: line 200
Always use stable, unique IDs in ForEach — avoid using array indices:
- Very specific: line 211
Never perform I/O, network calls, or heavy computation inside body
- Very specific: line 212
Use .task {} for async work — it cancels automatically when the view disappears
- Very specific: line 213
Use .sensoryFeedback() and .geometryGroup() sparingly in scroll views
- Very specific: line 236
Use #Preview macro with inline mock data for fast iteration:
“Common” is measured: kept by at least 6 in 10 of the 8 edited versions of this file we could read. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
SwiftUI Patterns
Modern SwiftUI patterns for building declarative, performant user interfaces on Apple platforms. Covers the Observation framework, view composition, type-safe navigation, and performance optimization.
When to Activate
- Building SwiftUI views and managing state (
@State,@Observable,@Binding) - Designing navigation flows with
NavigationStack - Structuring view models and data flow
- Optimizing rendering performance for lists and complex layouts
- Working with environment values and dependency injection in SwiftUI
State Management
Property Wrapper Selection
Choose the simplest wrapper that fits:
| Wrapper | Use Case |
@State | View-local value types (toggles, form fields, sheet presentation) |
@Binding | Two-way reference to parent's @State |
@Observable class + @State | Owned model with multiple properties |
@Observable class (no wrapper) | Read-only reference passed from parent |
@Bindable | Two-way binding to an @Observable property |
@Environment | Shared dependencies injected via .environment() |
@Observable ViewModel
Use @Observable (not ObservableObject) — it tracks property-level changes so SwiftUI only re-renders views that read the changed property:
@Observable
final class ItemListViewModel {
private(set) var items: [Item] = []
private(set) var isLoading = false
var searchText = ""
private let repository: any ItemRepository
init(repository: any ItemRepository = DefaultItemRepository()) {
self.repository = repository
}
func load() async {
isLoading = true
defer { isLoading = false }
items = (try? await repository.fetchAll()) ?? []
}
}View Consuming the ViewModel
struct ItemListView: View {
@State private var viewModel: ItemListViewModel
init(viewModel: ItemListViewModel = ItemListViewModel()) {
_viewModel = State(initialValue: viewModel)
}
var body: some View {
List(viewModel.items) { item in
ItemRow(item: item)
}
.searchable(text: $viewModel.searchText)
.overlay { if viewModel.isLoading { ProgressView() } }
.task { await viewModel.load() }
}
}Environment Injection
Replace @EnvironmentObject with @Environment:
// Inject
ContentView()
.environment(authManager)
// Consume
struct ProfileView: View {
@Environment(AuthManager.self) private var auth
var body: some View {
Text(auth.currentUser?.name ?? "Guest")
}
}View Composition
Extract Subviews to Limit Invalidation
Break views into small, focused structs. When state changes, only the subview reading that state re-renders:
struct OrderView: View {
@State private var viewModel = OrderViewModel()
var body: some View {
VStack {
OrderHeader(title: viewModel.title)
OrderItemList(items: viewModel.items)
OrderTotal(total: viewModel.total)
}
}
}ViewModifier for Reusable Styling
struct CardModifier: ViewModifier {
func body(content: Content) -> some View {
content
.padding()
.background(.regularMaterial)
.clipShape(RoundedRectangle(cornerRadius: 12))
}
}
extension View {
func cardStyle() -> some View {
modifier(CardModifier())
}
}Navigation
Type-Safe NavigationStack
Use NavigationStack with NavigationPath for programmatic, type-safe routing:
@Observable
final class Router {
var path = NavigationPath()
func navigate(to destination: Destination) {
path.append(destination)
}
func popToRoot() {
path = NavigationPath()
}
}
enum Destination: Hashable {
case detail(Item.ID)
case settings
case profile(User.ID)
}
struct RootView: View {
@State private var router = Router()
var body: some View {
NavigationStack(path: $router.path) {
HomeView()
.navigationDestination(for: Destination.self) { dest in
switch dest {
case .detail(let id): ItemDetailView(itemID: id)
case .settings: SettingsView()
case .profile(let id): ProfileView(userID: id)
}
}
}
.environment(router)
}
}Performance
Use Lazy Containers for Large Collections
LazyVStack and LazyHStack create views only when visible:
ScrollView {
LazyVStack(spacing: 8) {
ForEach(items) { item in
ItemRow(item: item)
}
}
}Stable Identifiers
Always use stable, unique IDs in ForEach — avoid using array indices:
// Use Identifiable conformance or explicit id
ForEach(items, id: \.stableID) { item in
ItemRow(item: item)
}Avoid Expensive Work in body
- Never perform I/O, network calls, or heavy computation inside
body - Use
.task {}for async work — it cancels automatically when the view disappears - Use
.sensoryFeedback()and.geometryGroup()sparingly in scroll views - Minimize
.shadow(),.blur(), and.mask()in lists — they trigger offscreen rendering
Equatable Conformance
For views with expensive bodies, conform to Equatable to skip unnecessary re-renders:
struct ExpensiveChartView: View, Equatable {
let dataPoints: [DataPoint] // DataPoint must conform to Equatable
static func == (lhs: Self, rhs: Self) -> Bool {
lhs.dataPoints == rhs.dataPoints
}
var body: some View {
// Complex chart rendering
}
}Previews
Use #Preview macro with inline mock data for fast iteration:
#Preview("Empty state") {
ItemListView(viewModel: ItemListViewModel(repository: EmptyMockRepository()))
}
#Preview("Loaded") {
ItemListView(viewModel: ItemListViewModel(repository: PopulatedMockRepository()))
}Anti-Patterns to Avoid
- Using
ObservableObject/@Published/@StateObject/@EnvironmentObjectin new code — migrate to@Observable - Putting async work directly in
bodyorinit— use.task {}or explicit load methods - Creating view models as
@Stateinside child views that don't own the data — pass from parent instead - Using
AnyViewtype erasure — prefer@ViewBuilderorGroupfor conditional views - Ignoring
Sendablerequirements when passing data to/from actors
References
See skill: swift-actor-persistence for actor-based persistence patterns.
See skill: swift-protocol-di-testing for protocol-based DI and testing with Swift Testing.
Other versions21 projects use a version of this.
Word for word · 12
- loulanyue/awesome-claude-notes★ 272100% same
- ronmkr/PromptBook★ 2100% same
- junimnjw/everything-claude-code★ 1100% same
- SamuelNDCE/claude-super-skill-library★ 1100% same
- TironFox/everything-claude-code★ 1100% same
- davidanthonyn/claude-skills★ 0100% same
- gesh75/claude-skills★ 0100% same
- MohamedEssam0-0/claude-skills★ 0100% same
- PeterYang888/claude-skills★ 0100% same
- renepf/claude-skills★ 0100% same
2 more not listed
Edited · 5
- Fmarzochi/EGC★ 61100% same
- georgekhananaev/claude-skills-vault★ 2899% same
- gongyijie85/dsh-ecc★ 898% same
- TsinHzl/claude-code-config★ 244% same
- WinterDDo/claude-skills★ 096% same
Wrote their own version · 4
- openai/plugins★ 7.4ksame name
- thienqo/ios-skills★ 4same name
- jasonfesta/design-agents★ 1same name
- agenticluke/swiftui-patterns-plus★ 0same name
How matches are found. Word for word: the exact same text. Edited: shares passages with this file (“99% same” means 99% of its five-word phrases also appear here; 10% or more counts). Their own version: similar meaning, or, weakest, the same name. We can’t tell which project had it first. Projects are counted among the 200 most-starred candidates, and mentions are links to the repository we found, up to 50 per site, so both counts are a floor.
Used alongsideProjects with it also use mcp-builder, frontend-design and 1 more.
Other files people use alongside this one.
Files found in the same public projects as a version of this one, more often than they turn up anywhere else. Each project counts once, large collections count for less, and this file's own repository is left out.
MicrosoftSkillmcp-builder
Guide for creating high-quality MCP (Model Context Protocol) servers that enable LLMs to interact with external services through well-designed tools. Use when building MCP servers to integrate external APIs or services, whether in Python (FastMCP) or Node/TypeScript (MCP SDK).
Also in 3 projects that use this
BlockSkillfrontend-design
Create distinctive, production-grade frontend interfaces with high design quality. Use this skill when the user asks to build web components, pages, or applications. Generates creative, polished code that avoids generic AI aesthetics.
Also in 3 projects that use this
SentrySkillskill-creator
Create new agent skills following the Agent Skills specification. Use when asked to "create a skill", "add a new skill", "write a skill", "make a skill", "build a skill", or scaffold a new skill with SKILL.md. Guides through requirements, writing, registration, and verification.
Also in 3 projects that use this
In this repository71 other files it gives its agents.
- .claude/rules/common/agents.mdAGENTS.md
- docs/agents.mdAGENTS.md
- CLAUDE.mdCLAUDE.md
- api-designSkill
- article-writingSkill
- backend-patternsSkill
- clickhouse-ioSkill
- coding-standardsSkill
- configure-eccSkill
- content-engineSkill
- content-hash-cache-patternSkill
- continuous-learningSkill
- continuous-learning-v2Skill
- cost-aware-llm-pipelineSkill
- cpp-coding-standardsSkill
- cpp-testingSkill
- database-migrationsSkill
- deployment-patternsSkill
- django-patternsSkill
- django-securitySkill
- django-tddSkill
- django-verificationSkill
- docker-patternsSkill
- e2e-testingSkill
- eval-harnessSkill
- foundation-models-on-deviceSkill
- frontend-patternsSkill
- frontend-slidesSkill
- golang-patternsSkill
- golang-testingSkill
- investor-materialsSkill
- investor-outreachSkill
- iterative-retrievalSkill
- java-coding-standardsSkill
- jpa-patternsSkill
- liquid-glass-designSkill
- market-researchSkill
- nutrient-document-processingSkill
- postgres-patternsSkill
- project-guidelines-exampleSkill
- python-patternsSkill
- python-testingSkill
- regex-vs-llm-structured-textSkill
- search-firstSkill
- security-reviewSkill
- security-scanSkill
- seo-auditSkill
- seo-competitor-pagesSkill
- seo-contentSkill
- seo-geoSkill
- seo-hreflangSkill
- seo-imagesSkill
- seo-pageSkill
- seo-planSkill
- seo-programmaticSkill
- seo-schemaSkill
- seo-sitemapSkill
- seoSkill
- seo-technicalSkill
- skill-stocktakeSkill
- The first 60 shown.
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

