Created
May 29, 2025 19:35
-
-
Save anettodev/39eda6309da4e8a30f558a6451a3bf67 to your computer and use it in GitHub Desktop.
.cursor/rules/swift.mdc
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| --- | |
| description: | |
| globs: *.swift | |
| alwaysApply: false | |
| --- | |
| # Swift Coding Guidelines | |
| ## File Structure and Documentation | |
| - If not already present, add this header to the beginning of each file: | |
| ```swift | |
| // | |
| // {Filename.swift} | |
| // {ProjectName} | |
| // Created by @ANETTO.DEV on {DATE}. | |
| // | |
| ``` | |
| - Use Swift 5.9+ for all new code | |
| - Reference official documentation: | |
| - [Swift.org Documentation](mdc:https:/www.swift.org/documentation) | |
| - [Apple Developer Documentation](mdc:https:/developer.apple.com/documentation/swift) | |
| - [Swift GitHub Repository](mdc:https:/github.com/swiftlang/swift) | |
| - Document public APIs with Swift-style documentation comments (triple-slash ///) | |
| - Use MARK comments to organize code sections: | |
| ```swift | |
| // MARK: - Properties | |
| // MARK: - Lifecycle | |
| // MARK: - Public Methods | |
| // MARK: - Private Methods | |
| ``` | |
| ## Code Style and Formatting | |
| - Follow [Google's Swift Style Guide](mdc:https:/google.github.io/swift) as primary reference | |
| - Alternative: [Kodeco's Swift Style Guide](mdc:https:/github.com/kodecocodes/swift-style-guide) | |
| - Use descriptive, Apple-friendly naming conventions: | |
| - Classes, structs, enums, protocols: `PascalCase` | |
| - Variables, properties, functions: `camelCase` | |
| - Start boolean variables with is/has/can/should/will | |
| - Use explicit access modifiers (`private`, `fileprivate`, `internal`, `public`) | |
| - Embrace Swift's type inference; avoid unnecessary type annotations | |
| - Prefer `let` over `var` to enforce immutability | |
| - Keep line length under 100 characters | |
| - Use early returns with `guard` statements for preconditions | |
| - Implement pattern matching for comprehensive switch statements | |
| - Use trailing closures only when improving readability | |
| - Align function parameters for better readability: | |
| ```swift | |
| func myFunction(firstParam: String, | |
| secondParam: Int, | |
| thirdParam: Bool) { | |
| // Implementation | |
| } | |
| ``` | |
| ## Swift Language Features | |
| - Favor structs, protocols, and protocol extensions over inheritance-based class hierarchies | |
| - Use enums with associated values for type-safe state representation | |
| - Implement `async/await` for asynchronous operations | |
| - Use property wrappers appropriately (`@Published`, `@Observable`, etc.) | |
| - Leverage Swift's Result type for error handling: | |
| ```swift | |
| func fetchData() async -> Result<Data, FetchError> { | |
| // Implementation | |
| } | |
| ``` | |
| - Implement proper error propagation with domain-specific errors: | |
| ```swift | |
| enum AppError: Error { | |
| case networkError(underlying: Error) | |
| case dataParsingError(message: String) | |
| case authenticationError | |
| } | |
| ``` | |
| - Use extensions to organize code by functionality | |
| - Implement protocol conformance in extensions | |
| - Use generics to create reusable, type-safe components | |
| - Utilize Swift's strong type system for compile-time safety | |
| ## Directory Structure | |
| - Well-organized directory structure: | |
| - **Features/**: Feature-specific files and folders | |
| - **Core/**: Core logic and services | |
| - **UI/**: Reusable UI components | |
| - **Models/**: Data models and types | |
| - **Networking/**: Network communication | |
| - **Utils/**: Utilities and helpers | |
| - **Resources/**: Assets and resources | |
| ## SwiftUI Best Practices | |
| ### State Management | |
| - Use the Observation framework for modern state management: | |
| - Annotate view models with `@Observable` for SwiftUI observation | |
| - Use `@State` only for local view state | |
| - Pass model references directly to child views | |
| - Use `@Binding` only when child views need write access to parent state | |
| - Use `@Environment` for app-wide or feature-wide shared state | |
| - Implement `@MainActor` for UI-updating code | |
| - Isolate state in dedicated observable objects | |
| ### Component Design | |
| - Use built-in SwiftUI components (List, NavigationView, TabView) for consistency | |
| - Leverage SF Symbols for icons to maintain Apple's design language | |
| - Design custom ViewModifiers for reusable styling: | |
| ```swift | |
| struct RoundedButtonStyle: ViewModifier { | |
| func body(content: Content) -> some View { | |
| content | |
| .padding() | |
| .background(Color.blue) | |
| .foregroundColor(.white) | |
| .cornerRadius(10) | |
| } | |
| } | |
| extension View { | |
| func roundedButton() -> some View { | |
| self.modifier(RoundedButtonStyle()) | |
| } | |
| } | |
| ``` | |
| - Create extension methods for view styling and behavior | |
| - Extract repeating view elements to dedicated components | |
| - Make custom components flexible and reusable | |
| ### Layout and Responsiveness | |
| - Master layout tools: | |
| - VStack, HStack, ZStack for structured layouts | |
| - Spacer and Padding for proper spacing | |
| - LazyVGrid and LazyHGrid for efficient grid layouts | |
| - GeometryReader for size-dependent layouts | |
| - Design UI to handle all screen sizes and orientations | |
| - Implement proper keyboard handling for text inputs | |
| - Use safe area and layout guides properly | |
| - Implement responsive designs that adapt to different devices | |
| ### Visual Design | |
| - Add visual flair with: | |
| - Shadows, gradients, and blurs | |
| - Custom shapes and paths | |
| - Animations using `.animation()` modifier | |
| - Transitions for view changes | |
| - Design for both light and dark mode | |
| - Use the asset catalog for colors with light/dark variants | |
| - Implement consistent spacing and alignment | |
| ### Interaction Design | |
| - Implement gestures (swipes, long presses, drags) | |
| - Add haptic feedback for important interactions | |
| - Create clear navigation patterns | |
| - Design responsive elements that provide feedback | |
| ### Performance Optimization | |
| - Profile regularly using Instruments to detect bottlenecks | |
| - Implement lazy loading for lists and resource-heavy content | |
| - Use stable identifiers in ForEach: | |
| ```swift | |
| ForEach(items, id: \.id) { item in | |
| ItemView(item: item) | |
| } | |
| ``` | |
| - Minimize view rebuilds by isolating state changes | |
| - Use `@ViewBuilder` for conditional view construction | |
| - Apply view modifiers in the correct order for optimal performance | |
| - Cache expensive computations | |
| - Avoid excessive view nesting | |
| ### Accessibility | |
| - Add accessibility labels, hints, and traits to all UI elements | |
| - Support Dynamic Type for text scaling | |
| - Implement proper VoiceOver navigation | |
| - Test with Accessibility Inspector | |
| - Ensure sufficient color contrast | |
| - Group related elements with accessibilityElement(children:) | |
| - Provide accessibility actions for custom gestures | |
| ## Networking | |
| - Separate request and response models into distinct files | |
| - Implement comprehensive error handling with domain-specific errors | |
| - Use strong typing for API endpoints | |
| - Leverage protocol-based networking for testability: | |
| ```swift | |
| protocol NetworkService { | |
| func fetch<T: Decodable>(endpoint: Endpoint) async throws -> T | |
| } | |
| ``` | |
| - Implement proper request and response logging | |
| - Use `async/await` for network calls | |
| - Implement proper cancellation for network tasks | |
| - Handle network connectivity changes gracefully | |
| - Add retry mechanisms for transient failures | |
| - Implement proper timeout handling | |
| ## Testing | |
| - Write unit tests for all business logic | |
| - Use Preview providers for rapid UI iteration: | |
| ```swift | |
| struct ContentView_Previews: PreviewProvider { | |
| static var previews: some View { | |
| ContentView() | |
| ContentView() | |
| .environment(\.colorScheme, .dark) | |
| ContentView() | |
| .previewDevice("iPhone SE (3rd generation)") | |
| } | |
| } | |
| ``` | |
| - Create snapshot tests for UI consistency | |
| - Implement UI tests for critical user flows | |
| - Mock dependencies for isolated testing | |
| - Structure tests using Given-When-Then or Arrange-Act-Assert patterns | |
| - Test edge cases and error scenarios | |
| - Use test-driven development when appropriate | |
| ## App Architecture | |
| - Follow MVVM or TCA (The Composable Architecture) for SwiftUI apps | |
| - Use dependency injection for testability and modularity | |
| - Implement proper separation of concerns | |
| - Create clear boundaries between UI, business logic, and data layers | |
| - Use coordinators or router patterns for navigation | |
| - Isolate side effects in dedicated components | |
| - Design for testability from the start | |
| ## Performance and Optimization | |
| - Profile the app regularly using Instruments | |
| - Optimize image loading and caching | |
| - Manage background tasks efficiently | |
| - Implement proper memory management | |
| - Reduce unnecessary view updates and re-renders | |
| - Monitor and optimize app launch time | |
| - Use Swift Concurrency for background operations | |
| - Implement proper disk and network caching | |
| - Optimize memory usage with appropriate data structures | |
| ## Security | |
| - Store sensitive data securely using Keychain | |
| - Implement proper certificate pinning for network calls | |
| - Follow Apple's security best practices | |
| - Encrypt data at rest when necessary | |
| - Validate all user inputs | |
| - Implement proper authentication and authorization | |
| - Protect against common vulnerabilities (XSS, CSRF, etc.) | |
| - Use secure coding practices | |
| ## Tool Integration | |
| - Use SwiftLint for enforcing style guidelines | |
| - Implement SPM (Swift Package Manager) for dependencies | |
| - Use XcodeGen or Tuist for project generation when needed | |
| - Leverage Swift macros for code generation | |
| - Implement CI/CD for continuous testing and delivery | |
| - Set up automated testing and deployment workflows | |
| - Use code coverage tools to measure test effectiveness | |
| ## Build and Release | |
| - Adopt a clear Git branching strategy | |
| - Follow a rigorous code review process | |
| - Set up CI/CD pipeline for automated builds and testing | |
| - Maintain thorough documentation for all major components | |
| - Aim for comprehensive unit test coverage to prevent regressions | |
| - Use proper versioning (Semantic Versioning) | |
| - Implement feature flags for gradual rollouts | |
| - Create comprehensive release notes | |
| ## Documentation | |
| - Document all public APIs with clear purpose and examples | |
| - Use Swift's built-in documentation syntax (///) | |
| - Include parameter descriptions and return value explanations | |
| - Document error cases and throwing functions | |
| - Use DocC for comprehensive documentation | |
| - Create usage examples for complex components | |
| - Document architectural decisions and patterns |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment