Swift

From G1Joshi/Agent-Skills · View interactive version

Swift is an AI agent skill from the GitHub repository G1Joshi/Agent-Skills. Expert Swift assistance covering Swift 6 strict concurrency, async/await, actors, protocols, generics, memory management with ARC, and SwiftUI integration. Use when writing iOS/macOS applications, debugging concurrency warnings, or building robust Swift codebases.

How to use this skill

Skill file

Swift

Modern Swift development with protocol-oriented programming and async/await.

When to Use

Quick Start

struct User: Identifiable, Codable {
    let id: UUID
    var name: String
    var email: String

    var displayName: String {
        name.capitalized
    }
}

Core Concepts

Modern Swift 6 Concurrency: Actors & Structured Tasks

Data-race safety guaranteed at compile time with Sendable enforcement and actors:

import Foundation

// Thread-safe state isolation via actor
actor AccountManager {
    private var balances: [UUID: Decimal] = [:]

    func deposit(to accountId: UUID, amount: Decimal) {
        guard amount > 0 else { return }
        balances[accountId, default: 0] += amount
    }

    func balance(for accountId: UUID) -> Decimal {
        balances[accountId, default: 0]
    }
}

// Structured concurrency with TaskGroup
func fetchUserMetrics(userIds: [UUID]) async throws -> [UUID: Decimal] {
    let manager = AccountManager()

    return try await withThrowingTaskGroup(of: (UUID, Decimal).self) { group in
        for id in userIds {
            group.addTask {
                let bal = await manager.balance(for: id)
                return (id, bal)
            }
        }

        var results: [UUID: Decimal] = [:]
        for try await (id, bal) in group {
            results[id] = bal
        }
        return results
    }
}

Protocol-Oriented Architecture & Primary Associated Types

Expressive type contracts using Swift 5.7+ some and any semantics:

// Protocol with primary associated type
protocol Repository<Entity>: Sendable {
    associatedtype Entity: Identifiable, Sendable
    func fetch(by id: Entity.ID) async throws -> Entity?
    func save(_ entity: Entity) async throws
}

struct User: Identifiable, Sendable {
    let id: UUID
    let name: String
}

final class InMemoryUserRepository: Repository {
    private var store: [UUID: User] = [:]

    func fetch(by id: UUID) async throws -> User? {
        store[id]
    }

    func save(_ entity: User) async throws {
        store[entity.id] = entity
    }
}

// Opaque return type using 'some' for static dispatch performance
func makeDefaultRepo() -> some Repository<User> {
    InMemoryUserRepository()
}

Result Builders & Custom DSLs

Constructing declarative hierarchies modeled after SwiftUI:

@resultBuilder
struct HTMLBuilder {
    static func buildBlock(_ components: String...) -> String {
        components.joined(separator: "
")
    }

    static func buildOptional(_ component: String?) -> String {
        component ?? ""
    }
}

func htmlDoc(@HTMLBuilder content: () -> String) -> String {
    "<html>
<body>
\(content())
</body>
</html>"
}

let page = htmlDoc {
    "<h1>Welcome to Swift 6</h1>"
    "<p>Safe, fast, and expressive systems programming.</p>"
}

Common Patterns

Modern Async/Await Network Request

Problem: Deeply nested completion handler callbacks and error propagation bugs in asynchronous code.

Solution:

func fetchUser(id: UUID) async throws -> User {
    let url = URL(string: "https://api.example.com/users/\(id)")!
    let (data, response) = try await URLSession.shared.data(from: url)

    guard let httpResponse = response as? HTTPURLResponse,
          httpResponse.statusCode == 200 else {
        throw NetworkError.invalidResponse
    }

    return try JSONDecoder().decode(User.self, from: data)
}

// Parallel execution
async let user = fetchUser(id: userId)
async let orders = fetchOrders(userId: userId)
let (userResult, ordersResult) = try await (user, orders)

Actors

Problem: Preventing concurrent data race bugs when mutating shared mutable state across asynchronous tasks.

Solution:

actor UserCache {
    private var cache: [UUID: User] = [:]

    func get(_ id: UUID) -> User? { cache[id] }
    func set(_ user: User) { cache[user.id] = user }
}

Best Practices

Do:

Don't:

Troubleshooting

| Error | Cause | Solution |

| ------------------------- | ------------------------------------ | -------------------- |

| unexpectedly found nil | Force unwrap of nil | Use optional binding |

| Actor-isolated property | Accessing actor from sync context | Use await |

| Sendable closure | Non-sendable type across concurrency | Make type Sendable |

References

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.