본문으로 건너뛰기
Skillpedia
일반 코딩48k · #5900

swift

하는 일

이 가이드는 Swift 언어의 모범 사례에 따라 더 효율적이고 올바른 Swift 코드를 작성하는 방법을 가르칩니다. '옵셔널'과 '동시성' 같은 기능을 효과적으로 사용하는 방법을 보여 줍니다.

사용하는 경우

  • ✓더 깔끔하고 안전한 Swift 코드를 쓰고 싶을 때.
  • ✓있을 수도 없을 수도 있는 값을 다루는 권장 방법(옵셔널)을 배우고 싶을 때.
  • ✓동시에 일어나는 작업(동시성)을 다루는 경우.

스킬 링크

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

복사해서 AI(Claude, ChatGPT, Cursor)에 붙여넣고 지침을 따르도록 요청하세요.

사용 방법

가장 쉬운 방법입니다. 메시지를 복사해 AI에 붙여넣으세요. AI가 스킬을 읽고 지침을 따릅니다.

바로 붙여넣을 수 있는 메시지

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.
AI가 이런 스킬을 알아서 찾아 쓰길 원하시나요?무료 Skillpedia MCP를 설치하세요. 한 줄이면 작업마다 스킬 15,000+개 중에서 검색합니다.1분 만에 설치 →

AI에게 요청하는 예시

“Swift 코드가 존재하지 않을 수도 있는 값을 올바르게 다루는지 어떻게 확인할 수 있나요?”

매주 새 스킬 5개. 읽는 데 1분.

작동 방식

이 가이드는 '나쁜' 코드 예시와 좋은 예시를 비교해 모범 사례를 보여 줍니다. Swift의 언어 도구를 더 지능적으로 사용해 흔한 실수를 피하는 데 중점을 둡니다.

기술 내용 (원본 SKILL.md)

작성자의 영어 원문을 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)

…
자주 묻는 질문

Swift의 '옵셔널'이란 무엇인가요?

변수가 값을 가질 수도 있고 아무것도 없을(nil) 수도 있다는 것을 나타내는 Swift의 방식입니다. 가이드는 이를 안전하게 다루는 방법을 보여 줍니다.

Swift의 '동시성'이란 무엇인가요?

여러 작업을 동시에 수행하는 능력입니다. 가이드는 최신 도구를 사용해 Swift에서 이를 효율적으로 하는 방법을 설명합니다.

Swift에서 '클래스' 대신 '구조체'를 쓰는 이유는 무엇인가요?

일반적으로 Swift에서는 단순한 데이터에 '구조체'를 선호합니다. 값을 복사하는 방식으로 동작해 더 안전하고 예측하기 쉽습니다. '클래스'는 공유와 정체성이 필요할 때 사용합니다.

상세 정보

작성자의 원본 설명

Language-specific super-code guidelines for swift.

repo: sickn33/agentic-awesome-skills

인기도

GitHub 스타
48k
순위
#5900
라이선스
MIT
업데이트
2026. 10. 15.

이 스킬이 유용한가요?

0

로그인 투표하려면 로그인하세요.

댓글

  • …

이 저장소의 다른 스킬

비슷한 스킬