DM
Technical reference

Swift Cheatsheet

Safe, expressive development for Apple platforms

Must Know

swift

Optionals

Unwrap optionals safely.

var nickname: String?
let displayName = nickname ?? "Guest"
if let nickname { print(nickname) }
swift

Struct and Protocol

Prefer value types unless shared identity is required.

protocol Identifiable { var id: UUID { get } }
struct User: Identifiable {
    let id: UUID
    var name: String
}

Important Patterns

swift

Async/Await

func loadUser() async throws -> User {
    let (data, response) = try await URLSession.shared.data(from: url)
    return try JSONDecoder().decode(User.self, from: data)
}
swift

Main Actor

UI state must be updated on the main actor.

@MainActor
final class UserViewModel: ObservableObject {
    @Published private(set) var user: User?
}

Useful Recipes

swift

Codable

struct User: Codable {
    let id: Int
    let displayName: String

    enum CodingKeys: String, CodingKey { case id; case displayName = "display_name" }
}
swift

Guard

Use guard for early exits and happy-path readability.

guard response.statusCode == 200 else {
    throw APIError.badStatus(response.statusCode)
}

Pitfalls & Production

swift

Avoid Retain Cycles

Escaping closures can strongly capture their owner.

service.load { [weak self] result in
    self?.handle(result)
}
swift

Error Context

Do not silently discard errors with try?.

do { try await save() }
catch let error as APIError { logger.error("Save failed: \(error)") }