Back to Skills

Swift Best Practices

| This skill should be used when writing or reviewing Swift code for iOS or macOS projects. Apply modern Swift 6+ best practices, concurrency patterns, API design guidelines, and migration strategies. Covers async/await, actors, MainActor, Sendable, typed throws, and Swift 6 bre…

swiftapiai
By secondsky
17928Updated 1 day agoTypeScriptMIT

Skill Content

# Swift Best Practices Skill

## Overview

Apply modern Swift development best practices focusing on Swift 6+ features, concurrency safety, API design principles, and code quality guidelines for iOS and macOS projects targeting macOS 15.7+.

## When to Use This Skill

Use this skill when:
- Writing new Swift code for iOS or macOS applications
- Reviewing Swift code for correctness, safety, and style
- Implementing Swift concurrency features (async/await, actors, MainActor)
- Designing Swift APIs and public interfaces
- Migrating code from Swift 5 to Swift 6
- Addressing concurrency warnings, data race issues, or compiler errors related to Sendable/isolation
- Working with modern Swift language features introduced in Swift 6 and 6.2

## SwiftLens MCP Integration (Claude Code)

This skill complements **SwiftLens MCP server** for semantic-level Swift code analysis.

**What SwiftLens Provides:**
- 15 tools for semantic Swift analysis using Apple's SourceKit-LSP
- Symbol lookup, cross-file references, type information
- Safe code modification and refactoring
- Compiler-grade understanding of Swift code structure

**What This Skill Provides:**
- Swift 6+ design patterns and best practices
- Concurrency strategies (async/await, actors, MainActor)
- API design guidelines and naming conventions
- Migration guidance (Swift 5 → Swift 6)

**Setup for Claude Code CLI:**

Create `.claude/mcps/swiftlens.json` in your Swift project:

```json
{
  "mcpServers": {
    "swiftlens": {
      "description": "SwiftLens MCP provides semantic Swift analysis via SourceKit-LSP",
      "command": "uvx",
      "args": ["swiftlens"]
    }
  }
}
```

**⚠️ Note**: This is **Claude Code** configuration (not Claude Desktop). See `references/swiftlens-mcp-claude-code.md` for complete setup guide, all 15 tools, index building, and usage examples.

**Workflow**: SwiftLens provides **runtime analysis** (what the code is doing), this skill provides **design expertise** (what the code should be doing).

## Core Guidelines

### Fundamental Principles

1. **Clarity at point of use** is paramount - evaluate designs by examining use cases, not just declarations
2. **Clarity over brevity** - compact code comes from the type system, not minimal characters
3. **Write documentation for every public declaration** - if you can't describe functionality simply, the API may be poorly designed
4. **Name by role, not type** - `var greeting = "Hello"` not `var string = "Hello"`
5. **Favour elegance through simplicity** - avoid over-engineering unless complexity genuinely warrants it

### Swift 6 Concurrency Model

Swift 6 enables complete concurrency checking by default with region-based isolation (SE-0414). The compiler now proves code safety, eliminating many false positives whilst catching real concurrency issues at compile time.

**Critical understanding:**
- **Async ≠ background** - async functions can suspend but don't automatically run on background threads
- Actors protect mutable shared state through automatic synchronisation
- `@MainActor` ensures UI-related code executes on the main thread
- Global actor-isolated types are automatically `Sendable`

### Essential Patterns

#### Async/Await
```swift
// Parallel execution with async let
func fetchData() async -> (String, Int) {
    async let stringData = fetchString()
    async let intData = fetchInt()
    return await (stringData, intData)
}

// Always check cancellation in long-running operations
func process(_ items: [Item]) async throws -> [Result] {
    var results: [Result] = []
    for item in items {
        try Task.checkCancellation()
        results.append(await process(item))
    }
    return results
}
```

#### MainActor for UI Code
```swift
// Apply at type level for consistent isolation
@MainActor
class ContentViewModel: ObservableObject {
    @Published var images: [UIImage] = []

    func fetchData() async throws {
        self.images = try await fetchImages()
    }
}

// Avoid MainActor.run when direct await works
await doMainActorStuff()  // Good
await MainActor.run { doMainActorStuff() }  // Unnecessary
```

#### Actor Isolation
```swift
actor DataCache {
    private var cache: [String: Data] = [:]

    func store(_ data: Data, forKey key: String) {
        cache[key] = data  // No await needed inside actor
    }

    nonisolated func cacheType() -> String {
        return "DataCache"  // No await needed - doesn't access isolated state
    }
}
```

### Common Pitfalls to Avoid

1. **Don't mark functions as `async` unnecessarily** - async calling convention has overhead
2. **Never use `DispatchSemaphore` with async/await** - risk of deadlock
3. **Don't create stateless actors** - use non-isolated async functions instead
4. **Avoid split isolation** - don't mix isolation domains within one type
5. **Check task cancellation** - long operations must check `Task.checkCancellation()`
6. **Don't assume async means background** - explicitly move work to background if needed
7. **Avoid excessive context switching** - group operations within same isolation domain

### API Design Quick Reference

#### Naming Conventions
- Types/protocols: `UpperCamelCase`
- Everything else: `lowerCamelCase`
- Protocols describing capabilities: `-able`, `-ible`, `-ing` suffixes (`Equatable`, `ProgressReporting`)
- Factory methods: Begin with `make` (`x.makeIterator()`)
- Mutating pairs: imperative vs past participle (`x.sort()` / `x.sorted()`)

#### Method Naming by Side Effects
- No side effects: Noun phrases (`x.distance(to: y)`)
- With side effects: Imperative verbs (`x.append(y)`, `x.sort()`)

#### Argument Labels
- Omit when arguments can't be distinguished: `min(number1, number2)`
- Value-preserving conversions omit first label: `Int64(someUInt32)`
- Prepositional phrases label at preposition: `x.removeBoxes(havingLength: 12)`
- Label all other arguments

### Swift 6 Breaking Changes

#### Must Explicitly Mark Types with @MainActor (SE-0401)
Property wrappers no longer infer actor isolation automatically.

```swift
@MainActor
struct LogInView: View {
    @StateObject private var model = ViewModel()
}
```

#### Global Variables Must Be Concurrency-Safe (SE-0412)
```swift
static let config = Config()  // Constant - OK
@MainActor static var state = State()  // Actor-isolated - OK
nonisolated(unsafe) var cache = [String: Data]()  // Unsafe - use with caution
```

#### Other Changes
- `@UIApplicationMain`/`@NSApplicationMain` deprecated (use `@main`)
- `any` required for existential types
- Import visibility requires explicit access control

### API Availability Patterns

```swift
// Basic availability
@available(macOS 15, iOS 18, *)
func modernAPI() { }

// Deprecation with message
@available(*, deprecated, message: "Use newMethod() instead")
func oldMethod() { }

// Renaming with auto-fix
@available(*, unavailable, renamed: "newMethod")
func oldMethod() { }

// Runtime checking
if #available(iOS 18, *) {
    // iOS 18+ code
}

// Inverted checking (Swift 5.6+)
if #unavailable(iOS 18, *) {
    // iOS 17 and lower
}
```

**Key differences:**
- `deprecated` - Warning, allows usage
- `obsoleted` - Error from specific version
- `unavailable` - Error, completely prevents usage

## How to Use This Skill

### When Writing Code

1. Apply naming conventions following role-based, clarity-first principles
2. Use appropriate isolation (`@MainActor` for UI, actors for mutable state)
3. Implement async/await patterns correctly with proper cancellation handling
4. Follow Swift 6 concurrency model - trust compiler's flow analysis
5. Document public APIs with clear, concise summaries

### When Reviewing Code

1. Check for concurrency safety violations
2. Verify proper actor isolation and Sendable conformance
3. Ensure async functions handle cancellation appropriately
4. Validate API naming follows Swift guidelines
5. Confirm availability annotations are correct for target platforms

### Code Quality Standards

- Minimise comments - code should be self-documenting where possible
- Avoid over-engineering and unnecessary abstractions
- Use meaningful variable names based on role, not type
- Follow established project architecture and patterns
- Prefer `count(where:)` over `filter().count`
- Use `InlineArray` for fixed-size, performance-critical data
- Trust compiler's concurrency flow analysis - avoid unnecessary `Sendable` conformances

## Resources

### references/

Detailed reference material to load when in-depth information is needed:

- **swiftlens-mcp-claude-code.md** - SwiftLens MCP server setup for Claude Code CLI, 15 semantic analysis tools, index building, usage examples, and integration workflows
- **api-design.md** - Complete API design conventions, documentation standards, parameter guidelines, and naming patterns
- **concurrency.md** - Detailed async/await patterns, actor best practices, common pitfalls, performance considerations, and thread safety patterns
- **swift6-features.md** - New language features in Swift 6/6.2, breaking changes, migration strategies, and modern patterns
- **availability-patterns.md** - Comprehensive `@available` attribute usage, deprecation strategies, and platform version management

Load these references when detailed information is needed beyond the core guidelines provided above.

## Platform Requirements

- Swift 6.0+ compiler for Swift 6 features
- Swift 6.2+ for InlineArray and enhanced concurrency features
- macOS 15.7+ with appropriate SDK
- iOS 18+ for latest platform features
- Use `#available` for runtime platform detection
- Use `@available` for API availability marking

How to use

  1. Copy the skill content above
  2. Create a .claude/skills directory in your project
  3. Save as .claude/skills/claude-skills-swift-best-practices.md
  4. Use /claude-skills-swift-best-practices in Claude Code to invoke this skill

Claude Code Skills Collection

170 production-ready skills for Claude Code CLI

Version 3.3.1 | Last Updated: 2026-05-14

<div align="center">

🔌 Platform Support

This repository uses Claude Plugin Patterns — natively supported by:

PlatformStatusNotes
Claude CodeNativeFull marketplace support
Factory DroidNativeFull marketplace support
</div> **For all other Platforms like opencode, codex and others, you can use https://github.com/enulus/OpenPackage **

A curated collection of battle-tested skills for building modern web applications with Cloudflare, AI integrations, React, Tailwind, and more.

PS: if skills.sh warns about any skill: Their scan process is a outdated LLM which flags newest versions pins (like in ZOD) as non existent and by that potentially malicous.


Quick Start

Marketplace Installation (Recommended)

# Add the marketplace
/plugin marketplace add https://github.com/secondsky/claude-skills

# Install individual skills as needed
/plugin install cloudflare-d1@claude-skills
/plugin install tailwind-v4-shadcn@claude-skills
/plugin install ai-sdk-core@claude-skills

See MARKETPLACE.md for complete catalog of all 170 skills.

Bulk Installation (Contributors)

# Clone the repository
git clone https://github.com/secondsky/claude-skills.git
cd claude-skills

# Install all 170 skills at once
./scripts/install-all.sh

# Or install individual skills
./scripts/install-skill.sh cloudflare-d1

Repository Structure

This repository contains 170 production-tested skills for Claude Code, each focused on a specific technology or capability.

Individual Skills: Each skill is a standalone unit with:

  • SKILL.md - Core knowledge and guidance
  • Templates - Working code examples
  • References - Extended documentation
  • Scripts - Helper utilities

Installation Options:

  1. Individual - Install only the skills you need via marketplace
  2. Bulk - Install all 170 skills using ./scripts/install-all.sh

Available Skills (170 Individual Skills)

Each skill is individually installable. Install only the skills you need.

Full Catalog: See MARKETPLACE.md for detailed listings.

Categories

CategorySkillsExamples
tooling29turborepo, plan-interview, code-review
frontend26nuxt-v4, nuxt-v5, tailwind-v4-shadcn, tanstack-query, nuxt-studio, maz-ui, threejs
cloudflare21cloudflare-d1, cloudflare-workers-ai, cloudflare-agents
ai20openai-agents, claude-api, ai-sdk-core
api16api-design-principles, graphql-implementation
web10hono-routing, firecrawl-scraper, web-performance
mobile7swift-best-practices, react-native-app, react-native-skills
database6drizzle-orm-d1, neon-vercel-postgres, supabase-postgres-best-practices
security6csrf-protection, access-control-rbac
auth4better-auth
testing4vitest-testing, playwright-testing
design4design-review, design-system-creation
woocommerce4woocommerce-backend-dev
cms4hugo, sveltia-cms, wordpress-plugin-core
architecture3microservices-patterns, architecture-patterns
data3sql-query-optimization, recommendation-engine
seo2seo-optimizer, seo-keyword-cluster-builder
documentation1technical-specification

How It Works

Auto-Discovery

Claude Code automatically checks ~/.claude/skills/ for relevant skills before planning tasks:

User: "Set up a Cloudflare Worker with D1 database"
           ↓
Claude: [Checks skills automatically]
           ↓
Claude: "Found cloudflare-d1 skills.
         These prevent 12 documented errors. Use them?"
           ↓
User: "Yes"
           ↓
Result: Production-ready setup, zero errors, ~65% token savings

Note: Due to token limits, not all skills may be visible at once. See ⚠️ Important: Token Limits below.

Skill Structure

Each skill includes:

skills/[skill-name]/
├── SKILL.md              # Complete documentation
├── .claude-plugin/
│   └── plugin.json       # Plugin metadata
├── templates/            # Ready-to-copy templates
├── scripts/              # Automation scripts
└── references/           # Extended documentation

Recent Additions

May 2026

Supply Chain Security (cross-cutting):

  • dependency-upgrade expanded with Socket CLI integration — proactive malicious package detection, typosquatting alerts, and CI/CD security gates. New 418-line reference guide, 2 GitHub Actions templates, and expanded supply chain security comparison (3 tools)
  • 31 skills now include "Secure Installation" guidance — contextually-tailored security sections across all high-risk skill categories (scaffolding, MCP/agent SDKs, multi-provider installs, Docker, CI/CD). Covers 8 Bun skills, 5 Nuxt skills, 6 Cloudflare skills, 4 AI/agent skills, and 8 frontend/tooling skills
  • Supply chain security is now a first-class cross-cutting concern woven into the skill collection — not a standalone topic

February - April 2026

Full-Stack Frameworks:

  • nuxt-v5 (v1.0.0) - Full Nuxt 5 support with 4 skills (core, data, server, production), 3 diagnostic agents, and interactive setup wizard
  • supabase-postgres-best-practices - 30 Postgres optimization rules from Supabase across 8 categories
  • threejs (v1.0.0) - 3D web graphics: scenes, geometries, shaders, animations, post-processing

Infrastructure:

  • JSON schema validation - Automated plugin.json validation with CI support
  • GitHub issue templates - Skill-specific issue templates for bug reports, feature requests, and submissions

Plugin Enhancements:

  • mutation-testing - Added Bun native runner support
  • dependency-upgrade - Added supply chain security content

December 2025 - January 2026

Frontend Expansion:

  • nuxt-studio (v1.0.0) - Visual CMS for Nuxt Content with live preview, OAuth auth, and R2 storage integration
  • maz-ui (v1.0.0) - 50+ Vue/Nuxt components with theming, i18n, form generation, and 14 composables

Developer Workflow:

  • plan-interview (v2.0.0) - Adaptive interview-driven spec generation with autonomous quality review
  • turborepo (v2.8.0) - Updated to official Vercel skill with enhanced monorepo build optimization

Mobile Development:

  • react-native-skills (v1.0.0) - React Native & Expo best practices with performance optimization patterns

Enhanced Authentication:

  • better-auth (v2.2.0) - Expanded to 18 framework integrations with 30+ authentication plugins

⚠️ Important: Token Limits

Skill Visibility Constraint

Claude Code has a 15,000 character limit for the total size of skill descriptions in the system prompt. This limit also applies to commands and agents.

What this means:

  • Not all 170 skills may be visible in Claude's context at once
  • Skills are loaded based on relevance and available token budget
  • You can verify how many skills Claude currently sees by asking: "How many skills do you see in your system prompt?"

Checking Visible Skills

To verify which skills are currently loaded:

# Ask Claude Code directly
"Check what skills/plugins you see in your system prompt"

Claude will report something like: "85 of 170 skills visible due to token limits"

Workaround: Increase Token Budget

You can double the headroom for skill descriptions by setting an environment variable:

# Increase limit to 30,000 characters
export SLASH_COMMAND_TOOL_CHAR_BUDGET=30000

# Then launch Claude Code
claude

This gives you approximately 2x more skill visibility in the system prompt.

Note: This is a temporary workaround. The Claude Code team is working on better solutions for skill discovery and loading.


Token Efficiency

MetricManual SetupWith SkillsSavings
Average Tokens12,000-15,0004,000-5,000~65%
Typical Errors2-4 per service0 (prevented)100%
Setup Time2-4 hours15-45 minutes~80%

Across all 170 skills: 400+ documented errors prevented.


Contributing

Prerequisites for Contributors

Install the official plugin development toolkit:

/plugin install plugin-dev@claude-code-marketplace

This provides:

  • /plugin-dev:create-plugin command (8-phase guided workflow)
  • 7 comprehensive skills (hooks, MCP, structure, agents, commands, skills)
  • 2 specialized agents (agent-creator, plugin-validator)

Quick Steps

  1. Create skill directory in plugins/
  2. Add SKILL.md with YAML frontmatter
  3. Run ./scripts/sync-plugins.sh
  4. Submit pull request

See CONTRIBUTING.md and PLUGIN_DEV_BEST_PRACTICES.md for detailed guidelines.


Documentation

DocumentPurpose
START_HERE.mdStart here! Quick navigation guide
PLUGIN_DEV_BEST_PRACTICES.mdRepository-specific best practices (marketplace, budget, quality)
MARKETPLACE.mdFull skill catalog and installation guide
MARKETPLACE_MANAGEMENT.mdTechnical infrastructure (plugin.json, scripts, validation)
CLAUDE.mdProject context and development standards
CONTRIBUTING.mdContribution guidelines

Links


Built with ❤️ by Claude Skills Maintainers

View source on GitHub