Command Palette

Search for a command to run...

UnylyUnyly
Назад к скиллам

swift

БесплатноБез исполняемых скриптовНе проверен

Swift programming patterns for iOS and macOS

miles990от miles990★ 26 звёзд на GitHub

Об этом скилле

Swift

Overview

Swift programming patterns including protocols, generics, async/await, and SwiftUI.


Swift Fundamentals

Structs and Classes

import Foundation

// Struct (value type, preferred for most cases)
struct User: Identifiable, Codable {
    let id: UUID
    var email: String
    var name: String
    var createdAt: Date

    // Memberwise initializer provided automatically
    // Custom initializer
    init(email: String, name: String) {
        self.id = UUID()
        self.email = email
        self.name = name
        self.createdAt = Date()
    }

    // Computed property
    var displayName: String {
        "\(name) <\(email)>"
    }

    // Mutating method (for structs)
    mutating func updateEmail(_ newEmail: String) {
        email = newEmail
    }
}

// Class (reference type)
class UserManager {
    static let shared = UserManager() // Singleton

    private var users: [UUID: User] = [:]

    private init() {}

    func add(_ user: User) {
        users[user.id] = user
    }

    func find(id: UUID) -> User? {
        users[id]
    }
}

// Actor (thread-safe reference type)
actor UserStore {
    private var users: [UUID: User] = [:]

    func add(_ user: User) {
        users[user.id] = user
    }

    func find(id: UUID) -> User? {
        users[id]
    }

    func count() -> Int {
        users.count
    }
}

Enums and Pattern Matching

// Enum with associated values
enum Result<Success, Failure: Error> {
    case success(Success)
    case failure(Failure)

    var isSuccess: Bool {
        if case .success = self { return true }
        return false
    }

    func map<NewSuccess>(_ transform: (Success) -> NewSuccess) -> Result<NewSuccess, Failure> {
        switch self {
        case .success(let value):
            return .success(transform(value))
        case .failure(let error):
            return .failure(error)
        }
    }
}

// Enum with raw values
enum Status: String, Codable, CaseIterable {
    case pending = "pending"
    case active = "active"
    case inactive = "inactive"

    var displayName: String {
        switch self {
        case .pending: return "Pending Review"
        case .active: return "Active"
        case .inactive: return "Inactive"
        }
    }
}

// Pattern matching
func process(_ result: Result<User, Error>) {
    switch result {
    case .success(let user) where user.email.contains("@admin"):
        print("Admin user: \(user.name)")
    case .success(let user):
        print("Regular user: \(user.name)")
    case .failure(let error):
        print("Error: \(error.localizedDescription)")
    }
}

// If-case pattern
if case .success(let user) = result {
    print(user.name)
}

// Guard-case pattern
func handleSuccess(_ result: Result<User, Error>) -> User? {
    guard case .success(let user) = result else {
        return nil
    }
    return user
}

Optionals

// Optional declaration
var name: String? = nil
var age: Int? = 25

// Optional binding
if let name = name {
    print("Name: \(name)")
}

// Multiple bindings
if let name = name, let age = age, age > 18 {
    print("\(name) is \(age) years old")
}

// Guard let (early exit)
func processUser(_ user: User?) -> String {
    guard let user = user else {
        return "No user"
    }
    return user.displayName
}

// Nil coalescing
let displayName = name ?? "Anonymous"

// Optional chaining
let uppercased = name?.uppercased()

// Map and flatMap
let nameLength = name.map { $0.count }
let parsed: Int? = "42".flatMap { Int($0) }

// Implicitly unwrapped (use sparingly)
var apiKey: String!

Protocols and Generics

Protocols

// Protocol definition
protocol Repository {
    associatedtype Entity: Identifiable

    func find(id: Entity.ID) async throws -> Entity?
    func findAll() async throws -> [Entity]
    func save(_ entity: Entity) async throws
    func delete(id: Entity.ID) async throws
}

// Protocol with default implementation
extension Repository {
    func findAll() async throws -> [Entity] {
        // Default implementation
        []
    }
}

// Protocol composition
protocol Named {
    var name: String { get }
}

protocol Aged {
    var age: Int { get }
}

typealias Person = Named & Aged

func greet(_ person: some Person) {
    print("Hello, \(person.name)!")
}

// Protocol with Self requirement
protocol Copyable {
    func copy() -> Self
}

// Conforming to protocols
struct UserRepository: Repository {
    typealias Entity = User

    func find(id: UUID) async throws -> User? {
        // Implementation
        nil
    }

    func save(_ entity: User) async throws {
        // Implementation
    }

    func delete(id: UUID) async throws {
        // Implementation
    }
}

Generics

// Generic function
func swap<T>(_ a: inout T, _ b: inout T) {
    let temp = a
    a = b
    b = temp
}

// Generic type
struct Stack<Element> {
    private var items: [Element] = []

    mutating fu
Полный SKILL.md на GitHub

Установить swift в Claude Code и Claude Desktop

Зарегайся, чтобы установить скилл

Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.

  • Открой команду установки в одну строку
  • Сохраняй скиллы в синхронизируемую библиотеку
  • Уведомления, когда скиллы обновляются
Зарегаться бесплатноУ меня уже есть аккаунт

Разрешённые инструменты

Инструменты, которые скиллу разрешено вызывать.

Без ограничений — скилл может использовать любой инструмент.

Вложенные файлы

templates/Package.swifttemplates/README.md

FAQ

Что делает скилл swift?

Swift programming patterns for iOS and macOS

Как установить скилл swift?

Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.

Скилл swift запускает скрипты?

Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.

Похожие скиллы

Сравнить swift с