swiftui-patterns
Use when building native iOS with SwiftUI - small composable views, observable state models, atomic components, Swift 6.2+ concurrency, and system styling…
от makifbaysal★ 123 звезды на GitHub
Установить swiftui-patterns в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Об этом скилле
SwiftUI Patterns
Overview
Native iOS (SwiftUI) is chosen when a task needs deep Apple-platform integration or the app is already native (see native-vs-flutter-decision). Same discipline as Flutter: small composed views, state out of the view, reusable atomic components.
Core principle: Views are a function of state. Data and business logic live in an observable model, not in the View.
Rules
- Small views, composed. Extract subviews as their own
Viewtypes (not@ViewBuilderfuncs) so each has its own body and preview. - State ownership is explicit:
@Statefor local ephemeral UI only (and it is alwaysprivate); app/business state in an@MainActor @Observablemodel injected viainit/@Environment. Views send intents to the model; the model owns the logic and the networking. - Atomic components: a shared component library (atoms → molecules → organisms) of reusable views. Reuse before building; grep before adding.
- System styling over hardcoded values: colors from the asset catalog /
Colorsemantic roles, spacing/typography from a tokens file (seemobile-design-system-foundation) — not scattered magic numbers. Support Dynamic Type and dark mode. #Previewevery reusable view in its key states (loading/data/error), and in the matrix: Dynamic Type.accessibility3, dark,traits: .landscapeLeft.- Value types (
struct) for models and view state; reference types only where identity is needed. - Never name a domain type
Task— it shadows_Concurrency.Task, which everyasync/.task {}call site needs; a rename (BoardItem,WorkItem, …) is a five-minute fix versus a confusing compile error later.
Concurrency
- Follow the target's default actor isolation: a new Xcode 26 project defaults to
@MainActorisolation, so a view model that touches UI state should be@MainActor @Observableexplicitly rather than relying on inference holding across Swift versions. - No GCD (
DispatchQueue.main.async, etc.) in new code —async/await,Task { },Task.sleep(for:). - Kick off async work from
.task { }on the view, notonAppear+ a detachedTask.
Worked Example
struct BoardItem: Identifiable, Sendable { let id: Int; let title: String } // never name a model `Task`
enum LoadState<T> { case loading, empty, data(T), failed(String) }
@MainActor @Observable final class ItemListModel {
private(set) var state: LoadState<[BoardItem]> = .loading
private let repo: any BoardItemRepository
init(repo: any BoardItemRepository) { self.repo = repo }
func load() async {
state = .loading
do { let items = try await repo.list(); state = items.isEmpty ? .empty : .data(items) }
catch { state = .failed(error.localizedDescription) }
}
}
struct ItemListScreen: View {
@State private var model: ItemListModel
init(model: ItemListModel) { _model = State(initialValue: model) }
var body: some View {
Group {
switch model.state {
case .loading: AppSpinner()
case .empty: ContentUnavailableView("No items yet", systemImage: "tray")
case .failed(let message):
ContentUnavailableView {
Label("Couldn't load items", systemImage: "exclamationmark.triangle")
} description: { Text(message) } actions: {
Button("Try again") { Task { await model.load() } }
}
case .data(let items): ItemList(items: items)
}
}
.task { await model.load() }
}
}
Typechecks with swiftc -swift-version 6 (verified). The original example's domain struct Task shadowed _Concurrency.Task, giving error: missing argument for parameter 'title' in call at every Task { } call site — renamed to BoardItem here. Note the explicit .empty case rendered with ContentUnavailableView and a retry action on .failed, and the init that seeds State(initialValue:) so the model can be injected.
Previews at the matrix (typechecked against the iOS 18 simulator SDK):
#Preview("Phone, AX3, dark") { ItemListScreen(model: .preview).environment(\.dynamicTypeSize, .accessibility3).preferredColorScheme(.dark) }
#Preview("Landscape", traits: .landscapeLeft) { ItemListScreen(model: .preview) }
For a layout that must switch at large accessibility sizes: typeSize.isAccessibilitySize ? AnyLayout(VStackLayout()) : AnyLayout(HStackLayout()). For an icon-only control: Button("Add to cart", systemImage: "cart.badge.plus", action:) with .labelStyle(.iconOnly) and .frame(minWidth: 44, minHeight: 44) (see mobile-accessibility).
Rules for testing
- Unit-test the
@Observablemodel with a mocked repository (no UI). - New tests in Swift Testing (
import Testing,@Test,#expect) where the target already uses Xcode 16+; XCTest stays for existing UI tests andapp.performAccessibilityAudit(). Test-first.
Modern API
- `foreg
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
FAQ
Что делает скилл swiftui-patterns?
Use when building native iOS with SwiftUI - small composable views, observable state models, atomic components, Swift 6.2+ concurrency, and system styling over hardcoded values
Как установить скилл swiftui-patterns?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл swiftui-patterns запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
theme-factory
AnthropicToolkit for styling artifacts with a theme. These artifacts can be slides, docs, reportings, HTML landing pages, etc. There are 10 pre-set themes with…
access
AnthropicManage Discord channel access — approve pairings, edit allowlists, set DM/group policy. Use when the user asks to pair, approve someone, check who's allowed…
configure
AnthropicSet up the Discord channel — save the bot token and review access policy. Use when the user pastes a Discord bot token, asks to configure Discord, asks "how…
access
AnthropicManage iMessage channel access — approve pairings, edit allowlists, set DM/group policy. Use when the user asks to pair, approve someone, check who's allowed…