Skip to content

Instantly share code, notes, and snippets.

@banagale
Created July 10, 2025 14:04
Show Gist options
  • Save banagale/50dde8d6c56929d07e8ad17dab01680f to your computer and use it in GitHub Desktop.
Save banagale/50dde8d6c56929d07e8ad17dab01680f to your computer and use it in GitHub Desktop.
a proposed sample claude for a swift project

Claude Swift/iOS Project Preferences

This file contains general preferences and guidelines for Claude when working on Swift/iOS/macOS projects. Include this file in any Swift project where you want consistent Claude behavior.

Code Style & Quality

Swift

  • Follow Swift API Design Guidelines
  • Use descriptive, Swift-style naming (e.g., isEnabled not getEnabled)
  • Prefer value types (structs) over reference types (classes) when appropriate
  • Use guard for early exits and unwrapping optionals
  • Leverage Swift's type inference where it improves readability
  • Use // MARK: - comments to organize code sections

Code Organization

  • One type per file (class, struct, enum, protocol)
  • Extensions in separate files for protocol conformance
  • Group related functionality using extensions
  • Order: Properties → Initializers → Methods → Extensions

SwiftLint Integration

  • Follow SwiftLint rules when configured in project
  • Document any disabled rules with clear reasoning
  • Use inline disabling sparingly: // swiftlint:disable:next

Attribution Guidelines

CRITICAL: Claude must NEVER add attribution to itself in any form.

Prohibited Attribution

  • ❌ Do NOT add "Generated with Claude" to commit messages
  • ❌ Do NOT add "Co-Authored-By: Claude" to commits
  • ❌ Do NOT add Claude attribution in JIRA, Confluence, or pull requests
  • ❌ Do NOT include AI/Claude references in code comments
  • ❌ Do NOT add emoji indicators like 🤖 to denote AI involvement

Correct Attribution

  • ✅ All changes should be solely attributed to the human user
  • ✅ The person running Claude is the author of all work

Swift-Specific Best Practices

Optionals & Safety

  • Use optional binding (if let, guard let) over force unwrapping
  • Provide meaningful default values with nil-coalescing (??)
  • Document why force unwrapping is safe when absolutely necessary
  • Use weak and unowned appropriately to avoid retain cycles

Memory Management

  • Prefer value types to avoid reference counting overhead
  • Use [weak self] or [unowned self] in closures as appropriate
  • Be mindful of retain cycles in delegates and callbacks
  • Profile with Instruments for memory leaks

Concurrency

  • Use modern Swift concurrency (async/await) for new code
  • Properly mark actors and @MainActor for UI updates
  • Handle Task cancellation appropriately
  • Avoid data races with proper synchronization

Error Handling

// Prefer throwing functions with descriptive errors
enum NetworkError: LocalizedError {
    case invalidURL
    case noData
    case decodingFailed
    
    var errorDescription: String? {
        switch self {
        case .invalidURL: return "Invalid URL provided"
        case .noData: return "No data received"
        case .decodingFailed: return "Failed to decode response"
        }
    }
}

// Use Result type for async callbacks when not using async/await
// Handle all error cases explicitly

iOS/macOS Development

UI Development

  • Use SwiftUI for new UI when minimum deployment target allows
  • Follow MVC/MVVM/MVP patterns consistently within project
  • Keep view controllers focused - extract logic to dedicated types
  • Use dependency injection over singletons

Auto Layout (UIKit)

  • Prefer programmatic constraints or Interface Builder consistently
  • Name constraints for debugging
  • Use stack views to simplify layouts
  • Test on multiple device sizes and orientations

SwiftUI Best Practices

  • Keep views small and focused
  • Extract complex views into separate structs
  • Use @StateObject for owned objects, @ObservedObject for injected
  • Minimize @State usage - prefer view models
  • Use preview providers effectively for development

Testing Guidelines

Unit Testing

  • Follow Arrange-Act-Assert pattern
  • Use XCTAssert family appropriately
  • Mock network calls and external dependencies
  • Test edge cases and error conditions
  • Aim for >80% coverage on business logic

UI Testing

  • Use accessibility identifiers for reliable element selection
  • Keep UI tests focused and fast
  • Test critical user flows
  • Use page object pattern for maintainability

Documentation

Code Documentation

  • Use triple-slash comments for public APIs
  • Include parameter descriptions and return values
  • Add code examples in doc comments
  • Use Xcode's documentation markup
/// Fetches user data from the API
/// - Parameters:
///   - userID: The unique identifier for the user
///   - completion: Callback with the user data or error
/// - Returns: Cancellable request token
/// - Note: This method requires authentication

Project Documentation

  • Maintain up-to-date README with setup instructions
  • Document third-party dependencies and their purpose
  • Include architecture decisions and patterns used
  • Provide sample code for common tasks

Dependency Management

Swift Package Manager (Preferred)

  • Use exact versions for direct dependencies
  • Document why specific versions are required
  • Regularly update for security patches
  • Avoid unnecessary dependencies

CocoaPods/Carthage (Legacy)

  • Commit Podfile.lock/Cartfile.resolved
  • Document pod-specific configurations
  • Keep podspec/cartfile clean and organized

Platform-Specific Guidelines

macOS

  • Always use COPYFILE_DISABLE=1 when creating tar archives
  • Handle sandboxing and entitlements appropriately
  • Test on multiple macOS versions

iOS

  • Support at least current and previous iOS version
  • Handle different device sizes and traits
  • Test on actual devices, not just simulator
  • Profile for performance and battery usage

Cross-Platform Code

  • Use conditional compilation for platform differences
  • Abstract platform-specific code behind protocols
  • Share code via frameworks or packages

Performance Optimization

When to Optimize

  • Profile first with Instruments
  • Focus on actual bottlenecks
  • Document performance improvements
  • Consider battery impact on mobile

Common Swift Performance Tips

  • Use lazy for expensive computed properties
  • Prefer contains over filter().isEmpty
  • Use value types to avoid ARC overhead
  • Be mindful of string concatenation in loops

Security Best Practices

Data Protection

  • Use Keychain for sensitive data, not UserDefaults
  • Enable App Transport Security
  • Validate all user inputs
  • Use proper encryption for stored data

API Keys & Secrets

  • Never commit API keys or secrets
  • Use environment variables or separate config files
  • Document how to obtain required keys
  • Use proper SSL pinning for sensitive APIs

General "Never" Rules for Swift

  1. Don't force unwrap without documenting why it's safe
  2. Don't ignore compiler warnings - fix or suppress with reason
  3. Don't use implicitly unwrapped optionals in new code
  4. Don't create massive view controllers - extract and delegate
  5. Don't ignore memory leaks - profile and fix retain cycles
  6. Don't block the main thread - use background queues
  7. Don't hardcode strings - use constants or localization
  8. Don't skip error handling - handle all failure cases
  9. Don't use global state - prefer dependency injection
  10. Don't commit commented-out code - use version control

Code Review Mindset

When reviewing or writing Swift code, consider:

  • Is this idiomatic Swift or fighting the language?
  • Are optionals handled safely throughout?
  • Will this create retain cycles or memory leaks?
  • Is the code testable with current architecture?
  • Does this follow platform conventions and guidelines?

Communication Style

Pull Requests & Code Reviews

  • Use professional, constructive language
  • Focus on the code, not the person
  • Provide specific examples for improvements
  • Acknowledge good patterns and solutions

Documentation & Comments

  • Write as a professional developer
  • Explain complex business logic
  • Document workarounds with issue links
  • Keep comments up-to-date with code changes

Remember: These are general Swift/iOS preferences. Always defer to project-specific guidelines in the project's own CLAUDE.md file when there are conflicts.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment