Chuyển đến nội dung
Skillpedia
Lập trình chung48k · #5900

swift

Skill này làm gì

Hướng dẫn này dạy bạn viết code Swift hiệu quả và đúng hơn, theo thực hành tốt nhất của ngôn ngữ. Nó chỉ cách dùng hiệu quả các tính năng như “Optionals” và “Concurrency”.

Khi nào nên dùng

  • ✓Khi bạn muốn viết code Swift sạch và an toàn hơn.
  • ✓Khi muốn học cách khuyến nghị để xử lý giá trị có thể không tồn tại (Optionals).
  • ✓Khi làm việc với các tác vụ chạy đồng thời (Concurrency).

Liên kết skill

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

Sao chép rồi dán vào AI của bạn (Claude, ChatGPT hoặc Cursor) và nhờ nó làm theo hướng dẫn.

Cách dùng

Cách dễ nhất: sao chép tin nhắn và dán vào AI của bạn. AI sẽ đọc skill và làm theo hướng dẫn.

Tin nhắn có sẵn để dán

Hãy dùng skill này để giúp tôi: https://github.com/sickn33/agentic-awesome-skills/blob/main/plugins/agentic-awesome-skills-claude/skills/super-code/swift/SKILL.md Đọc tệp SKILL.md tại liên kết đó và làm theo hướng dẫn cho việc của tôi.
Bạn muốn AI tự tìm những skill như thế này?Cài MCP Skillpedia miễn phí: chỉ một dòng, và AI sẽ tìm trong 15.000+ skill trước mỗi việc.Cài đặt trong 1 phút →

Ví dụ cách nhờ AI

“Làm sao để đảm bảo code Swift của tôi xử lý đúng các giá trị có thể không có mặt?”

5 skill mới mỗi tuần. Đọc chỉ 1 phút.

Cách hoạt động

Hướng dẫn so sánh các ví dụ code “xấu” với “tốt” để minh họa thực hành tốt nhất. Nó tập trung vào cách dùng các công cụ của Swift thông minh hơn để tránh lỗi thường gặp.

Nội dung kỹ thuật (SKILL.md gốc)

Lấy nguyên văn từ GitHub, do tác giả viết bằng tiếng Anh.

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)

…
Câu hỏi thường gặp

“Optionals” trong Swift là gì?

“Optionals” là cách Swift cho biết một biến có thể chứa giá trị hoặc không có gì (nil). Hướng dẫn chỉ cách xử lý điều này an toàn.

“Concurrency” trong Swift là gì?

“Concurrency” là khả năng thực hiện nhiều tác vụ cùng lúc. Hướng dẫn giải thích cách làm việc này hiệu quả trong Swift bằng các công cụ mới nhất.

Vì sao dùng “structs” thay vì “classes” trong Swift?

Nói chung, “structs” được ưu tiên trong Swift cho dữ liệu đơn giản vì chúng hoạt động bằng cách sao chép (ngữ nghĩa giá trị), giúp an toàn và dễ dự đoán hơn. “Classes” được dùng khi bạn cần chia sẻ và nhận diện đối tượng.

Chi tiết

Mô tả gốc của tác giả

Language-specific super-code guidelines for swift.

repo: sickn33/agentic-awesome-skills

Độ phổ biến

Sao GitHub
48k
Vị trí xếp hạng
#5900
Giấy phép
MIT
Cập nhật
15/10/2026

Skill này có hữu ích không?

0

Đăng nhập để bình chọn.

Bình luận

  • …

Thêm skill từ kho mã này

Skill tương tự