swift-expert
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseSwift Expert
Swift专家
Purpose
用途
Provides Apple ecosystem development expertise specializing in native iOS/macOS/visionOS applications using Swift 6, SwiftUI, and modern concurrency patterns. Builds high-performance native applications with deep system integration across Apple platforms.
提供基于Apple生态系统的开发专业知识,专注于使用Swift 6、SwiftUI和现代并发模式构建原生iOS/macOS/visionOS应用。打造可在Apple全平台实现深度系统集成的高性能原生应用。
When to Use
何时使用
- Building native iOS/macOS apps with SwiftUI and SwiftData
- Migrating legacy Objective-C/UIKit code to modern Swift
- Implementing advanced concurrency with Actors and structured Tasks
- Optimizing performance (Instruments, Memory Graph, Launch Time)
- Integrating system frameworks (HealthKit, HomeKit, WidgetKit)
- Developing for visionOS (Spatial Computing)
- Creating Swift server-side applications (Vapor, Hummingbird)
- 使用SwiftUI和SwiftData构建原生iOS/macOS应用
- 将遗留Objective-C/UIKit代码迁移至现代Swift
- 使用Actors和结构化Tasks实现高级并发
- 优化性能(Instruments、内存图、启动时间)
- 集成系统框架(HealthKit、HomeKit、WidgetKit)
- 为visionOS开发(空间计算)
- 构建Swift后端应用(Vapor、Hummingbird)
Examples
示例
Example 1: Modern SwiftUI Architecture
示例1:现代SwiftUI架构
Scenario: Rewriting a legacy UIKit app in modern SwiftUI.
Implementation:
- Adopted MVVM architecture with Combine
- Created reusable ViewComponents for consistency
- Implemented proper state management
- Added comprehensive accessibility support
- Built preview-driven development workflow
Results:
- 50% less code than UIKit version
- Improved testability (ViewModels easily tested)
- Better accessibility (VoiceOver support)
- Faster development with Xcode Previews
场景: 用现代SwiftUI重写遗留UIKit应用。
实现方案:
- 采用结合Combine的MVVM架构
- 创建可复用ViewComponents以保证一致性
- 实现合理的状态管理
- 添加全面的无障碍支持
- 构建基于预览的开发工作流
成果:
- 代码量比UIKit版本减少50%
- 可测试性提升(ViewModel易于测试)
- 无障碍体验优化(支持VoiceOver)
- 借助Xcode Previews提升开发速度
Example 2: Swift Concurrency Migration
示例2:Swift并发迁移
Scenario: Converting callback-based code to async/await.
Implementation:
- Identified all completion handler patterns
- Created async wrappers using @MainActor where needed
- Implemented structured concurrency for parallel operations
- Added proper error handling with throw/catch
- Used actors for protecting shared state
Results:
- 70% reduction in boilerplate code
- Eliminated callback hell and race conditions
- Improved code readability and maintainability
- Better memory management with structured tasks
场景: 将基于回调的代码转换为async/await模式。
实现方案:
- 识别所有完成处理程序模式
- 在需要的地方使用@MainActor创建异步包装器
- 为并行操作实现结构化并发
- 用throw/catch实现合理的错误处理
- 使用actors保护共享状态
成果:
- 样板代码减少70%
- 消除回调地狱和竞态条件
- 代码可读性和可维护性提升
- 借助结构化任务优化内存管理
Example 3: Performance Optimization
示例3:性能优化
Scenario: Optimizing a slow startup time and janky scrolling.
Implementation:
- Used Instruments to profile app launch
- Identified heavy initializers and deferred them
- Implemented lazy loading for resources
- Optimized images with proper caching
- Reduced view hierarchy complexity
Results:
- Launch time reduced from 4s to 1.2s
- Scrolling now consistently 60fps
- Memory usage reduced by 40%
- Improved App Store ratings
场景: 优化缓慢的启动时间和卡顿的滚动体验。
实现方案:
- 使用Instruments分析应用启动过程
- 识别重型初始化操作并延迟执行
- 为资源实现懒加载
- 通过合理缓存优化图片
- 简化视图层级结构
成果:
- 启动时间从4秒缩短至1.2秒
- 滚动帧率稳定保持60fps
- 内存占用减少40%
- App Store评分提升
Best Practices
最佳实践
SwiftUI Development
SwiftUI开发
- MVVM Architecture: Clear separation of concerns
- State Management: Use proper @StateObject/@ObservedObject
- Performance: Lazy loading, proper Equatable
- Accessibility: Build in from the start
- MVVM架构:清晰的关注点分离
- 状态管理:合理使用@StateObject/@ObservedObject
- 性能:懒加载、正确实现Equatable
- 无障碍:从开发初期就纳入考虑
Swift Concurrency
Swift并发
- Structured Concurrency: Use Task and TaskGroup
- Actors: Protect shared state with actors
- MainActor: Properly handle UI updates
- Error Handling: Comprehensive throw/catch patterns
- 结构化并发:使用Task和TaskGroup
- Actors:用actors保护共享状态
- MainActor:正确处理UI更新
- 错误处理:全面的throw/catch模式
Performance
性能优化
- Instruments: Profile regularly, don't guess
- Lazy Loading: Defer expensive operations
- Memory Management: Watch for strong reference cycles
- Optimize Images: Proper format, caching, sizing
- Instruments:定期分析,避免主观猜测
- 懒加载:延迟执行高开销操作
- 内存管理:警惕强引用循环
- 图片优化:合理的格式、缓存和尺寸
Platform Integration
平台集成
- System Frameworks: Use appropriate Apple frameworks
- Privacy: Follow App Store privacy requirements
- Extensions: Support widgets, shortcuts, etc.
- VisionOS: Consider spatial computing patterns
Do NOT invoke when:
- Building cross-platform apps with React Native/Flutter → Use
mobile-app-developer - Writing simple shell scripts (unless specifically Swift scripting) → Use or
bashpython-pro - Designing game assets → Use (though Metal/SceneKit is in scope)
game-developer
- 系统框架:使用合适的Apple框架
- 隐私合规:遵循App Store隐私要求
- 扩展支持:支持小组件、快捷指令等
- VisionOS:考虑空间计算模式
请勿在以下场景调用:
- 使用React Native/Flutter构建跨平台应用 → 请使用
mobile-app-developer - 编写简单Shell脚本(除非是专门的Swift脚本)→ 请使用或
bashpython-pro - 设计游戏资源 → 请使用(不过Metal/SceneKit相关内容在本技能范围内)
game-developer
Core Capabilities
核心能力
Swift Development
Swift开发
- Building native iOS/macOS applications with SwiftUI
- Implementing advanced Swift features (Actors, async/await, generics)
- Managing state with SwiftData and Combine
- Optimizing performance with Instruments
- 使用SwiftUI构建原生iOS/macOS应用
- 实现Swift高级特性(Actors、async/await、泛型)
- 用SwiftData和Combine管理状态
- 用Instruments优化性能
Apple Platform Integration
Apple平台集成
- Integrating system frameworks (HealthKit, HomeKit, WidgetKit)
- Developing for visionOS and spatial computing
- Managing app distribution (App Store, TestFlight)
- Implementing privacy and security best practices
- 集成系统框架(HealthKit、HomeKit、WidgetKit)
- 为visionOS和空间计算开发应用
- 管理应用分发(App Store、TestFlight)
- 实施隐私与安全最佳实践
Concurrency and Performance
并发与性能
- Implementing Swift 6 concurrency patterns
- Managing memory and preventing retain cycles
- Debugging performance issues with profiling tools
- Optimizing app launch time and battery usage
- 实现Swift 6并发模式
- 管理内存并避免保留循环
- 用分析工具调试性能问题
- 优化应用启动时间和电池消耗
Testing and Quality
测试与质量
- Writing unit tests with XCTest
- Implementing UI testing with XCUITest
- Managing test coverage and quality metrics
- Setting up CI/CD for Apple platforms
- 用XCTest编写单元测试
- 用XCUITest实现UI测试
- 管理测试覆盖率和质量指标
- 为Apple平台搭建CI/CD流程
Workflow 2: Swift 6 Concurrency (Actors)
工作流2:Swift 6并发(Actors)
Goal: Manage a thread-safe cache without locks.
Steps:
-
Define Actorswift
actor ImageCache { private var cache: [URL: UIImage] = [:] func image(for url: URL) -> UIImage? { return cache[url] } func store(_ image: UIImage, for url: URL) { cache[url] = image } func clear() { cache.removeAll() } } -
Usage (Async context)swift
class ImageLoader { private let cache = ImageCache() func load(url: URL) async throws -> UIImage { if let cached = await cache.image(for: url) { return cached } let (data, _) = try await URLSession.shared.data(from: url) guard let image = UIImage(data: data) else { throw URLError(.badServerResponse) } await cache.store(image, for: url) return image } }
目标: 无需锁即可管理线程安全的缓存。
步骤:
-
定义Actorswift
actor ImageCache { private var cache: [URL: UIImage] = [:] func image(for url: URL) -> UIImage? { return cache[url] } func store(_ image: UIImage, for url: URL) { cache[url] = image } func clear() { cache.removeAll() } } -
用法(异步上下文)swift
class ImageLoader { private let cache = ImageCache() func load(url: URL) async throws -> UIImage { if let cached = await cache.image(for: url) { return cached } let (data, _) = try await URLSession.shared.data(from: url) guard let image = UIImage(data: data) else { throw URLError(.badServerResponse) } await cache.store(image, for: url) return image } }
4. Patterns & Templates
4. 模式与模板
Pattern 1: Dependency Injection (Environment)
模式1:依赖注入(环境)
Use case: Injecting services into the SwiftUI hierarchy.
swift
// 1. Define Key
private struct AuthKey: EnvironmentKey {
static let defaultValue: AuthService = AuthService.mock
}
// 2. Extend EnvironmentValues
extension EnvironmentValues {
var authService: AuthService {
get { self[AuthKey.self] }
set { self[AuthKey.self] = newValue }
}
}
// 3. Use
struct LoginView: View {
@Environment(\.authService) var auth
func login() {
Task { await auth.login() }
}
}使用场景: 向SwiftUI层级中注入服务。
swift
// 1. 定义Key
private struct AuthKey: EnvironmentKey {
static let defaultValue: AuthService = AuthService.mock
}
// 2. 扩展EnvironmentValues
extension EnvironmentValues {
var authService: AuthService {
get { self[AuthKey.self] }
set { self[AuthKey.self] = newValue }
}
}
// 3. 使用
struct LoginView: View {
@Environment(\.authService) var auth
func login() {
Task { await auth.login() }
}
}Pattern 2: Coordinator (Navigation)
模式2:协调器(导航)
Use case: Decoupling navigation logic from Views.
swift
@Observable
class Coordinator {
var path = NavigationPath()
func push(_ destination: Destination) {
path.append(destination)
}
func pop() {
path.removeLast()
}
func popToRoot() {
path.removeLast(path.count)
}
}
enum Destination: Hashable {
case detail(Int)
case settings
}使用场景: 将导航逻辑与视图解耦。
swift
@Observable
class Coordinator {
var path = NavigationPath()
func push(_ destination: Destination) {
path.append(destination)
}
func pop() {
path.removeLast()
}
func popToRoot() {
path.removeLast(path.count)
}
}
enum Destination: Hashable {
case detail(Int)
case settings
}Pattern 3: Result Builder (DSL)
模式3:结果构建器(DSL)
Use case: Creating a custom DSL for configuring API requests.
swift
@resultBuilder
struct RequestBuilder {
static func buildBlock(_ components: URLQueryItem...) -> [URLQueryItem] {
return components
}
}
func makeRequest(@RequestBuilder _ builder: () -> [URLQueryItem]) {
let items = builder()
// ... construct URL
}
// Usage
makeRequest {
URLQueryItem(name: "limit", value: "10")
URLQueryItem(name: "sort", value: "desc")
}使用场景: 创建用于配置API请求的自定义DSL。
swift
@resultBuilder
struct RequestBuilder {
static func buildBlock(_ components: URLQueryItem...) -> [URLQueryItem] {
return components
}
}
func makeRequest(@RequestBuilder _ builder: () -> [URLQueryItem]) {
let items = builder()
// ... 构造URL
}
// 用法
makeRequest {
URLQueryItem(name: "limit", value: "10")
URLQueryItem(name: "sort", value: "desc")
}6. Integration Patterns
6. 集成模式
backend-developer:
backend-developer:
- Handoff: Backend provides gRPC/REST spec → Swift Expert generates Codable structs.
- Collaboration: Handling pagination (cursors) and error envelopes.
- Tools: .
swift-openapi-generator
- 交接:后端提供gRPC/REST规范 → Swift专家生成Codable结构体。
- 协作:处理分页(游标)和错误封装。
- 工具:。
swift-openapi-generator
ui-designer:
ui-designer:
- Handoff: Designer provides Figma → Swift Expert uses to replicate.
HStack/VStack - Collaboration: Defining Design System (Color, Typography extensions).
- Tools: Xcode Previews.
- 交接:设计师提供Figma文件 → Swift专家使用进行还原。
HStack/VStack - 协作:定义设计系统(颜色、排版扩展)。
- 工具:Xcode Previews。
mobile-app-developer:
mobile-app-developer:
- Handoff: React Native team needs a native module (e.g., Apple Pay) → Swift Expert writes the Swift-JS bridge.
- Collaboration: exposing native UIViews to React Native.
- 交接:React Native团队需要原生模块(如Apple Pay)→ Swift专家编写Swift-JS桥接层。
- 协作:向React Native暴露原生UIViews。