Swift架构
Mattakushi4322026-10-26查看 132复制 1076
何时激活:iOS/macOS 应用架构、MVVM、TCA、Clean Architecture、依赖注入、Swift 应用中的模块化设计
📘如何使用这个技能
- 1复制技能内容·点击上方「Copy SKILL.md」复制全部内容,或 Download 下载到本地
- 2打开你的 AI 客户端·支持 Claude Code、Trae、Cursor、ChatGPT、DeepSeek、Kimi 等任意 AI 助手
- 3粘贴为系统提示/知识文件·Claude Code:放入 .claude/skills/ 目录;普通对话:作为首条消息发送并说「请严格按这份技能文档执行」
- 4直接提出你的需求·AI 会按技能定义的工作流、格式和约束来处理,无需再解释背景
💡 提示:技能生效后,每次对话只需一句需求,AI 会按 SKILL.md 的流程执行。
SKILL.md5345 chars
---
name: swift-architecture
description: "When to activate: iOS/macOS app architecture, MVVM, TCA, Clean Architecture, dependency injection, modular design in Swift apps"
origin: zakr
metadata:
namespace: zakr/devtools-pack
version: 1.0.0
category: engineering
language: swift
platforms: [claude-code, codex, gemini-cli, cursor, aider, windsurf]
---
# Swift App Architecture Patterns
## MVVM with SwiftUI
```swift
// Model — pure data, no UI dependencies
struct Article: Identifiable, Codable {
let id: UUID
let title: String
let body: String
let publishedAt: Date
}
// ViewModel — transforms model for display, owns async operations
@MainActor
final class ArticleListViewModel: ObservableObject {
@Published private(set) var articles: [Article] = []
@Published private(set) var isLoading = false
@Published var errorMessage: String?
private let repository: any ArticleRepository
init(repository: any ArticleRepository) {
self.repository = repository
}
func load() async {
isLoading = true
defer { isLoading = false }
do {
articles = try await repository.fetchAll()
} catch {
errorMessage = error.localizedDescription
}
}
}
// View — purely declarative, no business logic
struct ArticleListView: View {
@StateObject private var vm: ArticleListViewModel
init(repository: any ArticleRepository) {
_vm = StateObject(wrappedValue: ArticleListViewModel(repository: repository))
}
var body: some View {
Group {
if vm.isLoading { ProgressView() }
else { List(vm.articles) { ArticleRow(article: $0) } }
}
.task { await vm.load() }
.alert("Error", isPresented: .constant(vm.errorMessage != nil)) { }
message: { Text(vm.errorMessage ?? "") }
}
}
```
## Repository Pattern
```swift
protocol ArticleRepository {
func fetchAll() async throws -> [Article]
func fetch(id: UUID) async throws -> Article?
func save(_ article: Article) async throws
}
struct RemoteArticleRepository: ArticleRepository {
let client: APIClient
func fetchAll() async throws -> [Article] {
try await client.get("/articles", as: [Article].self)
}
func fetch(id: UUID) async throws -> Article? {
try await client.get("/articles/\(id)", as: Article.self)
}
func save(_ article: Article) async throws {
try await client.post("/articles", body: article) as Article
}
}
// In-memory implementation for tests/previews
final class InMemoryArticleRepository: ArticleRepository {
var articles: [Article] = []
func fetchAll() async throws -> [Article] { articles }
func fetch(id: UUID) async throws -> Article? { articles.first { $0.id == id } }
func save(_ article: Article) async throws { articles.append(article) }
}
```
## Dependency Injection Container
```swift
// Using point-free/swift-dependencies style
import Dependencies
extension DependencyValues {
var articleRepository: any ArticleRepository {
get { self[ArticleRepositoryKey.self] }
set { self[ArticleRepositoryKey.self] = newValue }
}
}
private enum ArticleRepositoryKey: DependencyKey {
static let liveValue: any ArticleRepository = RemoteArticleRepository(client: .live)
static let testValue: any ArticleRepository = InMemoryArticleRepository()
static let previewValue: any ArticleRepository = InMemoryArticleRepository(articles: .preview)
}
// Usage in ViewModel
@MainActor
final class ArticleListViewModel: ObservableObject {
@Dependency(\.articleRepository) var repository
}
```
## Clean Architecture Layers
```
Presentation (SwiftUI views + ViewModels)
↓
Domain (Use Cases / Interactors)
↓
Data (Repositories → Remote + Local)
```
```swift
// Domain layer — use case
struct FetchArticlesUseCase {
let remote: any ArticleRepository
let local: any ArticleRepository
func execute() async throws -> [Article] {
do {
let articles = try await remote.fetchAll()
for article in articles { try await local.save(article) }
return articles
} catch {
// Fallback to local cache
return try await local.fetchAll()
}
}
}
```
## Modular Feature Design
```swift
// Each feature is a standalone SPM module
// Feature/ArticleFeature/Sources/ArticleListView.swift
public struct ArticleListView: View {
public init(store: ArticleStore) { self.store = store }
private let store: ArticleStore
// ...
}
// App target wires features together
import ArticleFeature
import ProfileFeature
@main
struct MyApp: App {
var body: some Scene {
WindowGroup {
TabView {
ArticleListView(store: .live)
ProfileView(store: .live)
}
}
}
}
```
## Common Anti-Patterns
- **Fat ViewControllers / fat Views** — move business logic to ViewModel or UseCase
- **Views depending on networking** — always go through ViewModel → Repository
- **Singleton abuse** — use DI instead; singletons make testing hard
- **Circular module dependencies** — extract shared types to a `Core` module
- **Tight coupling between features** — communicate via protocols or shared events, not direct imports