Swift Cursor Rules: iOS Development Architecture & Testing
Swift cursor rules for iOS covering architecture, SwiftUI/UIKit, state management, async/await, testing with XCTest and XCUITest, performance-aware code generation.
Overview
Professional cursor rules for Swift that emphasize clean iOS architecture, SwiftUI/UIKit patterns, and concurrency with async/await. These rules help AI assistants generate maintainable, testable Swift code with clear context and platform boundaries.
Note:
Focus on SwiftUI/UIKit structure, state management, dependency injection, XCTest/XCUITest, and performance-conscious code generation.
Rules Configuration
.cursor/rules/swift.mdc
---
description: Enforces best practices for Swift development with context-aware generation, modern patterns, and maintainable iOS architecture. Clean, efficient, and secure code.
globs: **/*.swift
---
# Swift Best Practices
You are an expert in Swift programming for iOS and macOS. You understand modern architecture, SwiftUI/UIKit, and the importance of providing complete context in code generation.
### Context-Aware Code Generation
- Provide complete module context including imports and type declarations
- Include relevant configuration files (Package.swift, project.pbxproj) when scaffolding
- Generate complete function signatures with typed parameters and return values
- Include documentation following Swift markup
- Explain how a component fits the larger app architecture
### Code Style and Structure
- Follow Swift API Design Guidelines and clean code principles
- Organize modules with clear boundaries (Views, ViewModels, Models, Services)
- Use modern Swift features (property wrappers, result builders, async/await)
- Keep formatting consistent using SwiftFormat or similar tools
### Framework Best Practices
- Apply SwiftUI/UIKit patterns appropriately
- Use dependency injection and composition
- Configure navigation and routing cleanly
- Manage state predictably
- Implement robust error handling and logging
- Set up XCTest for unit and integration tests
### Testing and Quality
- Write unit tests with proper context
- Add integration tests for critical flows
- Use protocol-based mocking
- Include UI tests with XCUITest
- Add performance tests for key components
### Security and Performance
- Validate and sanitize inputs
- Use Keychain for secure storage
- Handle app permissions safely
- Apply caching strategies where appropriate
- Optimize memory usage and battery impact
### Example
```swift
protocol UserServiceProtocol {
func findUser(byEmail email: String) async throws -> User?
}
struct User: Codable {
let id: UUID
let email: String
}
actor UserService: UserServiceProtocol {
private let apiClient: APIClientProtocol
private let cache: CacheProtocol
init(apiClient: APIClientProtocol, cache: CacheProtocol) {
self.apiClient = apiClient
self.cache = cache
}
func findUser(byEmail email: String) async throws -> User? {
if let cachedUser = try? await cache.get("user:\(email)") as? User {
return cachedUser
}
do {
let user = try await apiClient.get("/users", query: ["email": email]) as User
try? await cache.set("user:\(email)", value: user)
return user
} catch {
throw APIError.userNotFound
}
}
}
class UserServiceTests: XCTestCase {
var service: UserService!
var mockAPIClient: MockAPIClient!
var mockCache: MockCache!
override func setUp() {
super.setUp()
mockAPIClient = MockAPIClient()
mockCache = MockCache()
service = UserService(apiClient: mockAPIClient, cache: mockCache)
}
func testFindUserByEmail_WhenUserExists() async throws {
let email = "[email protected]"
let user = User(id: UUID(), email: email)
mockAPIClient.mockResponse = user
let result = try await service.findUser(byEmail: email)
XCTAssertEqual(result?.email, email)
XCTAssertEqual(mockAPIClient.lastPath, "/users")
XCTAssertEqual(mockAPIClient.lastQuery["email"] as? String, email)
}
func testFindUserByEmail_WhenUserNotFound() async throws {
let email = "[email protected]"
mockAPIClient.mockError = APIError.userNotFound
do {
_ = try await service.findUser(byEmail: email)
XCTFail("Expected error")
} catch {
XCTAssertEqual(error as? APIError, .userNotFound)
}
}
}
Feature Highlights
SwiftUI Architecture
Views, ViewModels, and Services with clean boundaries
Async/Await Concurrency
Lifecycle-aware tasks and cancellation safety
Secure Storage
Keychain usage for sensitive data
Testing Built-In
Unit, integration, and UI tests with XCTest/XCUITest
Performance Focus
Efficient rendering and memory awareness for mobile
Platform APIs
Safe use of iOS capabilities and permissions
Installation
Choose Your IDE
Select the appropriate file path based on your development environment.
Create the Rules File
Create the cursor rules file in your project:
Create file: .cursor/rules/swift.mdc
Add the Rules Configuration
Copy the rules configuration above into your newly created file.
Start Building
Your AI assistant will now follow Swift best practices automatically.
Swift-Specific Rules
Cursor rules in Swift provide intelligent navigation and manipulation designed for iOS development. These patterns help you work efficiently across SwiftUI/UIKit, concurrency, and app architecture.
Code Navigation
- Jump to SwiftUI views and UIKit controllers
- Move between ViewModels and Services
- Quick access to lifecycle methods and tasks
Smart Selection
- Select SwiftUI view hierarchies and modifiers
- Expand selection to include property wrappers
- Smart optional and result handling selection
Code Manipulation
- Quick view insertion and modifier updates
- Automated state handling and binding wiring
- Task management and cancellation patterns
Use Cases
iOS Apps
Modern iOS apps with SwiftUI/UIKit and MVVM architecture
API Clients
Robust API clients with URLSession, Combine, and async/await
Data Persistence
Core Data or SQLite with migrations and caching strategies
Background Work
Background tasks, notifications, and secure storage handling
Configuration
Customize Swift-specific cursor rules in your settings:
{
"swift.cursorRules": {
"swiftuiNavigation": true,
"concurrencyAware": true,
"iosLifecycle": true,
"optionalSafety": true
}
}
Related Resources
Related Articles
JavaScript Cursor Rules: ES6+ Development Best Practices
Cursor rules for JavaScript development enforcing ES6+ standards, React best practices, and clean code principles with AI assistance for production-ready code.
Mobile Framework Cursor Rules for iOS and Android Development
Master cursor rules for React Native, Flutter, Swift, and Kotlin. Platform-specific best practices for efficient cross-platform and native mobile development.
Next.js Cursor Rules: Server Components, Routing, Fetching
Next.js cursor rules enforce server-first patterns, file routing, components, and efficient data fetching. Context-aware practices for maintainable code