Skip to content
Skillpedia
General coding48k Β· #5900

swift

What it does

This guide teaches you how to write more efficient and correct Swift code, following the language's best practices. It shows how to effectively use features like 'Optionals' and 'Concurrency'.

When to use it

  • βœ“When you want to write cleaner and safer Swift code.
  • βœ“To learn the recommended ways to handle values that may or may not exist (Optionals).
  • βœ“When working with tasks that happen at the same time (Concurrency).

Skill link

https://github.com/sickn33/agentic-awesome-skills/blob/main/plugins/agentic-awesome-skills-claude/skills/super-code/swift/SKILL.md

Copy it and paste it into your AI (Claude, ChatGPT or Cursor), asking it to follow the instructions.

How to use

The easiest way: copy the message and paste it into your AI. It reads the skill and follows the instructions.

Ready-to-paste message

Use this skill to help me: https://github.com/sickn33/agentic-awesome-skills/blob/main/plugins/agentic-awesome-skills-claude/skills/super-code/swift/SKILL.md Read the SKILL.md file at that link and follow its instructions for my task.
Want your AI to find skills like this on its own?Install the free Skillpedia MCP: one line, and it searches 15,000+ skills before each task.Install in 1 minute β†’

Example of what to ask your AI

β€œHow can I ensure my Swift code correctly handles values that might not be present?”

5 new skills a week. 1 minute to read.

How it works

The guide compares 'bad' code examples with 'good' ones to illustrate best practices. It focuses on how to use Swift's language tools more intelligently to avoid common mistakes.

Technical content (original SKILL.md)

Original text by the author, straight from GitHub.

Swift: Idiomatic Efficiency Reference

When to Use

  • Use this skill when the task matches this description: Language-specific super-code guidelines for swift.

Table of Contents

  1. Optionals
  2. Collections & Functional Transforms
  3. Value vs Reference Types
  4. Error Handling
  5. Concurrency
  6. Protocol-Oriented Design
  7. Anti-patterns specific to Swift

1. Optionals {#optionals}

// ❌ Force unwrap
let name = user.name!

// βœ… β€” guard or if-let
guard let name = user.name else { return }
// ❌ Nested if-let pyramid
if let user = fetchUser() {
    if let address = user.address {
        if let city = address.city {
            display(city)
        }
    }
}

// βœ… β€” chained optional binding
if let city = fetchUser()?.address?.city {
    display(city)
}
// or guard-let for early exit
guard let city = fetchUser()?.address?.city else { return }
display(city)
// ❌ Ternary for default
let name = user.name != nil ? user.name! : "Unknown"

// βœ…
let name = user.name ?? "Unknown"
// ❌ Optional map when if-let is clearer for side effects
user.name.map { display($0) }

// βœ… β€” map for transforms, if-let for side effects
let upper = user.name.map { $0.uppercased() }
if let name = user.name { display(name) }

2. Collections & Functional Transforms {#collections}

// ❌ Imperative filter + map
var result: [String] = []
for item in items {
    if item.isActive { result.append(item.name.uppercased()) }
}

// βœ…
let result = items
    .filter(\.isActive)
    .map { $0.name.uppercased() }
// ❌ Manual dictionary construction
var dict: [String: User] = [:]
for user in users { dict[user.id] = user }

// βœ…
let dict = Dictionary(uniqueKeysWithValues: users.map { ($0.id, $0) })
// or with possible duplicates:
let dict = Dictionary(grouping: users, by: \.department)
// ❌ Checking isEmpty then accessing first
if !items.isEmpty { process(items[0]) }

// βœ…
if let first = items.first { process(first) }
// ❌ Index-based loop
for i in 0..<items.count { process(items[i]) }

// βœ…
for item in items { process(item) }
// with index:
for (i, item) in items.enumerated() { process(i, item) }

Use key paths (\.isActive) as closure shorthand where supported.


3. Value vs Reference Types {#value-types}

// ❌ Class for plain data (reference semantics where value semantics suffice)
class Point {
    var x: Double
    var y: Double
    init(x: Double, y: Double) { self.x = x; self.y = y }
}

// βœ…
struct Point { var x, y: Double }
// ❌ Large struct copied repeatedly (performance hit)
struct HugeData { var buffer: [UInt8] /* thousands of elements */ }
func process(_ data: HugeData) { ... } // copies entire buffer

// βœ… β€” use class or pass inout for mutation
func process(_ data: inout HugeData) { ... }
// or use copy-on-write wrapper for large value types

Default to struct. Use class when you need identity, inheritance, or reference semantics.


4. Error Handling {#errors}

// ❌ Using optionals to mask errors
func parse(_ input: String) -> Data? { ... } // caller doesn't know why it failed

// βœ…
func parse(_ input: String) throws -> Data { ... }
// ❌ try! in production code
let data = try! JSONDecoder().decode(User.self, from: jsonData)

// βœ…
do {
    let data = try JSONDecoder().decode(User.self, from: jsonData)
} catch {
    logger.error("decode failed: \(error)")
    throw AppError.decodingFailed(underlying: error)
}
// ❌ Generic Error type
enum AppError: Error { case generic(String) }

// βœ… β€” specific, actionable error cases
enum AppError: Error {
    case networkUnreachable
    case invalidInput(field: String, reason: String)
    case unauthorized
}
// ❌ Catching all errors and ignoring
do { try riskyOperation() } catch { }

// βœ…
do {
    try riskyOperation()
} catch let error as NetworkError {
    handleNetworkError(error)
} catch {
    throw error // rethrow unknown
}

5. Concurrency {#concurrency}

// ❌ Callback-based async (pyramid of doom)
fetchUser { user in
    fetchPosts(for: user) { posts in
        fetchComments(for: posts.first!) { comments in
            display(comments)
        }
    }
}

// βœ… (Swift 5.5+)
let user = try await fetchUser()
let posts = try await fetchPosts(for: user)

…
FAQ

What are 'Optionals' in Swift?

'Optionals' are a way in Swift to indicate that a variable might hold a value or might hold nothing (be nil). The guide shows how to handle this safely.

What is 'Concurrency' in Swift?

'Concurrency' is the ability to perform multiple tasks at the same time. The guide explains how to do this efficiently in Swift using the latest tools.

Why use 'structs' over 'classes' in Swift?

Generally, 'structs' are preferred in Swift for simple data because they work by copying (value semantics), which can be safer and more predictable. 'Classes' are used when you need sharing and identity.

Details

Original description by the author

Language-specific super-code guidelines for swift.

repo: sickn33/agentic-awesome-skills

Popularity

GitHub stars
48k
Ranking position
#5900
License
MIT
Updated
10/15/2026

Is this skill useful?

0

Sign in to vote.

Comments

  • …

More skills from this repository

Similar skills