Learn  /  Cheat sheets

Swift cheat sheet

Modern Swift syntax at a glance, on one printable page.

Cheat sheet5 min readUpdated 30 September 2026
SwiftiOS
All cheat sheets and guides
All guides and cheat sheets

Constants and variables

Swift
let name = "Alessandro"      // constant
var count = 0                // variable
let price: Double = 3.5      // explicit type
let msg = "Total: \(count)"  // interpolation

Optionals

Swift
var email: String? = nil
if let email { print(email) }
guard let email else { return }
let display = email ?? "No email"
let length = email?.count

Collections

Swift
var items = ["Flat white", "Croissant"]
items.append("Cold brew")
var stock: [String: Int] = ["FW-01": 12]
stock["CR-02"] = 5
let unique: Set = [1, 2, 2, 3]   // {1, 2, 3}

Higher-order functions

Swift
let totals = [12.5, 40, 8]
totals.map { $0 * 1.2 }
totals.filter { $0 > 10 }
totals.reduce(0, +)
totals.sorted(by: >)
orders.compactMap(\.email)

Control flow

Swift
for (i, item) in items.enumerated() { print(i, item) }
for n in 1...5 { }
while count < 10 { count += 1 }
switch status {
case .paid: print("Paid")
case .refunded, .cancelled: print("Closed")
default: break
}

Functions and closures

Swift
func total(_ items: [Double], vat: Double = 0.2) -> Double {
    items.reduce(0, +) * (1 + vat)
}
let double: (Int) -> Int = { $0 * 2 }

Structs and classes

Swift
struct Product {            // value type
    let sku: String
    var price: Decimal
    mutating func discount(_ p: Decimal) { price *= (1 - p) }
}
final class Basket {        // reference type
    var items: [Product] = []
}

Enums

Swift
enum Status: String, Codable {
    case paid, refunded, cancelled
}
enum PaymentResult {
    case success(Decimal)
    case failure(String)
}

Protocols

Swift
protocol Priced { var price: Decimal { get } }
extension Product: Priced {}
func sum(_ xs: [some Priced]) -> Decimal {
    xs.reduce(0) { $0 + $1.price }
}

Errors

Swift
enum OrderError: Error { case empty }
func checkout(_ b: Basket) throws -> Decimal {
    guard !b.items.isEmpty else { throw OrderError.empty }
    return b.items.reduce(0) { $0 + $1.price }
}
do { try checkout(basket) } catch { print(error) }

Async/await

Swift
func load() async throws -> [Order] {
    let (data, _) = try await URLSession.shared.data(from: url)
    return try JSONDecoder().decode([Order].self, from: data)
}
async let a = load()
async let b = load()
let (x, y) = try await (a, b)   // run in parallel

Codable

Swift
struct Order: Codable {
    let orderId: Int
    let total: Decimal
}
let d = JSONDecoder()
d.keyDecodingStrategy = .convertFromSnakeCase
let order = try d.decode(Order.self, from: data)

Alessandro Ecclesie AgazziWritten by Alessandro Ecclesie Agazzi, analytics engineer in London. Updated 30 September 2026. About me

Found this useful?

New guides and "what's new" explainers on data and AI land here regularly. Follow along on LinkedIn, or share this one with a colleague.