thecodex.expert · The Codex Family of Knowledge
Snippets

Swift Snippets

13 idiomatic Swift patterns — copy, paste, adapt.

Swift 5.10+ 13 snippets Verified
Swiftoptionals.swift
Optionals: if let, guard let, map, and ??
func findUser(id: Int) -> String? {
    id > 0 ? "User\(id)" : nil
}

func processUser(id: Int) -> String {
    // guard let: unwrap or return early — value usable after guard
    guard let name = findUser(id) else {
        return "No user found"
    }
    // name is String (non-optional) here
    return "Hello, \(name)!"
}

// Optional chaining: returns nil if any step is nil
struct Address { let city: String }
struct User { let name: String; let address: Address? }

let user: User? = User(name: "Alice", address: Address(city: "Mumbai"))
let city = user?.address?.city  // Optional("Mumbai") or nil

// nil coalescing: provide default
let display = city ?? "Unknown"  // "Mumbai"

// map: transform if non-nil
let upper = city.map { $0.uppercased() }  // Optional("MUMBAI")

// flatMap: avoid double-wrapping
let text: String? = "  hello  "
let trimmed: String? = text.flatMap { $0.isEmpty ? nil : $0.trimmingCharacters(in: .whitespaces) }

// compactMap: filter out nils from array
let strings = ["1", "two", "3", "four"]
let numbers = strings.compactMap { Int($0) }
print(numbers)  // [1, 3]
Swiftstructs_value_types.swift
Structs and value semantics
struct Point {
    var x: Double
    var y: Double
    
    // mutating: modifies self — required for structs
    mutating func translate(dx: Double, dy: Double) {
        x += dx
        y += dy
    }
    
    func distance(to other: Point) -> Double {
        sqrt(pow(x - other.x, 2) + pow(y - other.y, 2))
    }
    
    static let origin = Point(x: 0, y: 0)
    
    // Computed property
    var magnitude: Double { sqrt(x*x + y*y) }
}

// Value semantics: assignment copies
var p1 = Point(x: 1, y: 2)
var p2 = p1      // independent copy
p2.translate(dx: 5, dy: 5)
print(p1)  // Point(x: 1.0, y: 2.0) — unchanged
print(p2)  // Point(x: 6.0, y: 7.0)

// Extension: add methods without modifying source
extension Point: CustomStringConvertible {
    var description: String { "(\(x), \(y))" }
}

// Extension on stdlib type
extension Double {
    var degrees: Double { self * 180 / .pi }
    var radians: Double { self * .pi / 180 }
}

print(p1.distance(to: Point.origin))   // √5 ≈ 2.236
print(45.0.radians)                     // 0.785...
Swiftenums.swift
Enums with associated values and Result
// Enum with associated values
enum NetworkResult<T> {
    case success(T)
    case failure(Error)
    case loading(progress: Double)
}

func handleResult<T>(_ result: NetworkResult<T>) where T: CustomStringConvertible {
    switch result {
    case .success(let data):
        print("Data: \(data)")
    case .failure(let error):
        print("Error: \(error.localizedDescription)")
    case .loading(let progress):
        print("Loading: \(Int(progress * 100))%")
    }
}

// Built-in Result type
func divide(_ a: Double, by b: Double) -> Result<Double, DivisionError> {
    guard b != 0 else { return .failure(.divisionByZero) }
    return .success(a / b)
}

enum DivisionError: Error {
    case divisionByZero
    var localizedDescription: String { "Cannot divide by zero" }
}

// Pattern matching
let result = divide(10, by: 2)
if case .success(let value) = result { print(value) }   // 5.0

// if case with binding
switch divide(10, by: 0) {
case .success(let v): print("Got \(v)")
case .failure(let e): print("Failed: \(e.localizedDescription)")
}

// CaseIterable: enumerate all cases
enum Direction: CaseIterable { case north, south, east, west }
print(Direction.allCases.count)  // 4
Swiftprotocols.swift
Protocols, default implementations, and some/any
protocol Drawable {
    var description: String { get }
    func draw() -> String
    func area() -> Double
}

// Protocol extension: default implementation
extension Drawable {
    func describe() -> String {
        "\(description): area=\(area().formatted(.number.precision(.fractionLength(2))))"
    }
}

struct Circle: Drawable {
    let radius: Double
    var description: String { "Circle(r=\(radius))" }
    func draw() -> String { "○" }
    func area() -> Double { .pi * radius * radius }
}

struct Rectangle: Drawable {
    let width, height: Double
    var description: String { "Rect(\(width)×\(height))" }
    func draw() -> String { "□" }
    func area() -> Double { width * height }
}

// some: opaque type — specific type known to compiler, not caller (zero-cost)
func makeShape() -> some Drawable { Circle(radius: 5) }

// any: existential — any conforming type at runtime (type erasure overhead)
func totalArea(_ shapes: [any Drawable]) -> Double {
    shapes.reduce(0) { $0 + $1.area() }
}

// Protocol composition
protocol Named { var name: String { get } }
func greet(_ thing: some Drawable & Named) {
    print("\(thing.name): \(thing.draw())")
}

let shapes: [any Drawable] = [Circle(radius: 5), Rectangle(width: 4, height: 6)]
print(totalArea(shapes))  // ~102.5
Swiftclosures.swift
Closures: trailing syntax, capture lists, @escaping
// Trailing closure syntax — last argument moved outside parentheses
let nums = [5, 3, 8, 1, 9, 2]
let sorted = nums.sorted { $0 < $1 }          // shorthand argument names
let evens  = nums.filter { $0 % 2 == 0 }      // [8, 2]
let doubled = nums.map { $0 * 2 }

// Function returning a closure
func makeMultiplier(factor: Int) -> (Int) -> Int {
    return { $0 * factor }   // captures factor
}

let triple = makeMultiplier(factor: 3)
print(triple(5))  // 15

// @escaping: closure outlives the function call
var storedClosure: (() -> Void)?
func store(_ closure: @escaping () -> Void) {
    storedClosure = closure   // closure escapes — must be @escaping
}

// Capture list: [weak self] breaks retain cycles
class ViewController {
    var onAction: (() -> Void)?
    
    func setup() {
        onAction = { [weak self] in
            guard let self else { return }
            self.handleAction()  // safe — won't retain self
        }
    }
    
    func handleAction() { print("action") }
}

// Autoclosure: wraps expression in a closure
func logIfEnabled(_ condition: Bool, _ message: @autoclosure () -> String) {
    if condition { print(message()) }   // message() only called if condition is true
}
logIfEnabled(true, "Expensive computation: \(Array(1...1000).reduce(0, +))")
Swiftcodable.swift
Codable: JSON encoding and decoding
import Foundation

struct User: Codable {
    let id: Int
    let name: String
    let email: String
    let isAdmin: Bool
    let createdAt: Date
    
    // Custom JSON key names
    enum CodingKeys: String, CodingKey {
        case id, name, email
        case isAdmin = "is_admin"
        case createdAt = "created_at"
    }
}

let user = User(id: 1, name: "Alice", email: "alice@example.com",
                isAdmin: false, createdAt: Date())

// Encode to JSON
let encoder = JSONEncoder()
encoder.outputFormatting = .prettyPrinted
encoder.dateEncodingStrategy = .iso8601
let data = try! encoder.encode(user)
print(String(data: data, encoding: .utf8)!)

// Decode from JSON
let json = """
{"id":2,"name":"Bob","email":"bob@example.com","is_admin":true,"created_at":"2026-06-10T12:00:00Z"}
""".data(using: .utf8)!

let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .iso8601
let decoded = try! decoder.decode(User.self, from: json)
print(decoded.name, decoded.isAdmin)  // Bob true

// Decode array
let arrayJson = "[{\"id\":1,\"name\":\"Alice\",\"email\":\"a@b.c\",\"is_admin\":false,\"created_at\":\"2026-01-01T00:00:00Z\"}]".data(using: .utf8)!
let users = try! decoder.decode([User].self, from: arrayJson)
Swiftasync_await.swift
async/await and concurrent tasks
import Foundation

func fetchUser(id: Int) async throws -> String {
    try await Task.sleep(nanoseconds: 100_000_000)  // non-blocking 100ms
    if id <= 0 { throw URLError(.badURL) }
    return "User\(id)"
}

// Sequential: total ~200ms
func sequential() async throws {
    let user1 = try await fetchUser(id: 1)  // waits
    let user2 = try await fetchUser(id: 2)  // waits
    print(user1, user2)
}

// Concurrent with async let: total ~100ms
func concurrent() async throws {
    async let user1 = fetchUser(id: 1)   // starts immediately
    async let user2 = fetchUser(id: 2)   // starts immediately, parallel
    let (u1, u2) = try await (user1, user2)   // wait for both
    print(u1, u2)
}

// TaskGroup: dynamic number of concurrent tasks
func loadAll(ids: [Int]) async throws -> [String] {
    try await withThrowingTaskGroup(of: String.self) { group in
        for id in ids {
            group.addTask { try await fetchUser(id: id) }
        }
        var results: [String] = []
        for try await result in group {
            results.append(result)
        }
        return results
    }
}

// Unstructured task (fire-and-forget)
func startBackgroundWork() {
    Task {
        if let user = try? await fetchUser(id: 99) {
            print("Background: \(user)")
        }
    }
}
Swiftactors.swift
Actors for thread-safe state
// actor: serialises access to its mutable state — no data races
actor Counter {
    private var value = 0
    private var history: [Int] = []
    
    func increment() {
        value += 1
        history.append(value)
    }
    
    func decrement() {
        value -= 1
        history.append(value)
    }
    
    var current: Int { value }   // actor property — read requires await from outside
    func getHistory() -> [Int] { history }
}

// @MainActor: guarantees execution on main thread — for UI
@MainActor
class ViewModel {
    var title = "Loading..."
    var isLoading = false
    
    func loadData() async {
        isLoading = true
        let data = await fetchFromNetwork()  // can suspend off main
        title = data          // back on main thread — safe
        isLoading = false
    }
    
    nonisolated func fetchFromNetwork() async -> String {
        try? await Task.sleep(nanoseconds: 100_000_000)
        return "Data loaded"
    }
}

// Accessing actor state from outside requires await
let counter = Counter()
Task {
    await counter.increment()
    await counter.increment()
    let current = await counter.current   // await required
    print("Count: \(current)")            // Count: 2
}
Swifterror_handling.swift
Error handling: throw, do-catch, and Result
// Custom errors conforming to Error
enum ValidationError: Error, LocalizedError {
    case tooShort(min: Int, got: Int)
    case tooLong(max: Int, got: Int)
    case invalidCharacters
    
    var errorDescription: String? {
        switch self {
        case .tooShort(let min, let got):
            return "Too short: minimum \(min) chars, got \(got)"
        case .tooLong(let max, let got):
            return "Too long: maximum \(max) chars, got \(got)"
        case .invalidCharacters:
            return "Contains invalid characters"
        }
    }
}

func validateUsername(_ name: String) throws -> String {
    guard name.count >= 3 else { throw ValidationError.tooShort(min: 3, got: name.count) }
    guard name.count <= 20 else { throw ValidationError.tooLong(max: 20, got: name.count) }
    guard name.allSatisfy({ $0.isLetter || $0.isNumber || $0 == "_" }) else {
        throw ValidationError.invalidCharacters
    }
    return name.lowercased()
}

// do-catch
do {
    let username = try validateUsername("Al")
    print("Valid: \(username)")
} catch let e as ValidationError {
    print("Validation failed: \(e.localizedDescription ?? "")")
} catch {
    print("Unknown error: \(error)")
}

// try? — convert to Optional
let safe = try? validateUsername("alice_123")  // Optional("alice_123")
let fail = try? validateUsername("x")           // nil

// Result for explicit error handling
func validate(_ name: String) -> Result<String, ValidationError> {
    Result { try validateUsername(name) }
}
Swiftcollections.swift
Collections: map, filter, reduce, Dictionary
struct Student { let name: String; let grade: Int; let subject: String }

let students = [
    Student(name: "Alice", grade: 92, subject: "Math"),
    Student(name: "Bob",   grade: 75, subject: "Science"),
    Student(name: "Carol", grade: 88, subject: "Math"),
    Student(name: "Dave",  grade: 95, subject: "Science"),
]

// filter + sorted + map
let topStudents = students
    .filter { $0.grade >= 85 }
    .sorted { $0.grade > $1.grade }
    .map { "\($0.name): \($0.grade)" }
print(topStudents)  // ["Dave: 95", "Alice: 92", "Carol: 88"]

// reduce
let average = students.reduce(0.0) { $0 + Double($1.grade) } / Double(students.count)

// Dictionary grouping
let bySubject = Dictionary(grouping: students) { $0.subject }
bySubject.forEach { subject, list in
    print("\(subject): \(list.map(\.name))")
}

// flatMap on sequences
let matrix = [[1,2,3],[4,5,6],[7,8,9]]
let flat = matrix.flatMap { $0 }   // [1,2,3,4,5,6,7,8,9]

// zip
let names = ["Alice", "Bob", "Carol"]
let scores = [95, 87, 92]
let ranking = zip(names, scores).map { "\($0): \($1)" }

// Dictionary operations
var wordCount: [String: Int] = [:]
"the quick brown fox the fox".split(separator: " ").forEach {
    wordCount[String($0), default: 0] += 1   // safe increment
}
print(wordCount["the"]!)  // 2
Swiftgenerics.swift
Generics with constraints and associated types
// Generic function with constraint
func maximum<T: Comparable>(_ a: T, _ b: T) -> T { a > b ? a : b }

// Generic struct
struct Stack<Element> {
    private var items: [Element] = []
    
    mutating func push(_ item: Element) { items.append(item) }
    
    mutating func pop() -> Element? { items.popLast() }
    
    var top: Element? { items.last }
    var isEmpty: Bool { items.isEmpty }
    var count: Int { items.count }
}

// Protocol with associated type
protocol Container {
    associatedtype Item
    var count: Int { get }
    func item(at index: Int) -> Item
}

// Where clause: multiple constraints
func findFirst<C: Collection>(_ collection: C, where predicate: (C.Element) -> Bool) -> C.Element?
where C.Element: Equatable {
    collection.first(where: predicate)
}

// some and any with generics
func makeContainer() -> some Container {   // opaque — specific type hidden
    Stack<Int>()
}

func printAll(_ containers: [any Container]) {   // heterogeneous array
    for c in containers { print(c.count) }
}

print(maximum(3, 7))           // 7
print(maximum("apple", "fig")) // fig

var s = Stack<String>()
s.push("hello"); s.push("world")
print(s.pop()!)   // "world"
Swiftproperty_wrappers.swift
Property wrappers and computed properties
// Custom property wrapper
@propertyWrapper
struct Clamped<T: Comparable> {
    private var value: T
    let range: ClosedRange<T>
    
    var wrappedValue: T {
        get { value }
        set { value = min(max(newValue, range.lowerBound), range.upperBound) }
    }
    
    init(wrappedValue: T, _ range: ClosedRange<T>) {
        self.range = range
        self.value = min(max(wrappedValue, range.lowerBound), range.upperBound)
    }
}

struct Settings {
    @Clamped(0...100) var volume: Int = 50
    @Clamped(0.0...1.0) var brightness: Double = 0.5
}

var settings = Settings()
settings.volume = 150   // clamped to 100
settings.volume = -10   // clamped to 0
print(settings.volume)  // 0

// Computed properties with didSet / willSet
class Temperature {
    var celsius: Double = 0 {
        didSet { print("Changed from \(oldValue)°C to \(celsius)°C") }
        willSet { print("About to change to \(newValue)°C") }
    }
    
    var fahrenheit: Double {
        get { celsius * 9/5 + 32 }
        set { celsius = (newValue - 32) * 5/9 }
    }
}

let temp = Temperature()
temp.celsius = 100
print(temp.fahrenheit)  // 212.0
temp.fahrenheit = 32
print(temp.celsius)     // 0.0
Swiftstring_interpolation.swift
String interpolation, formatting, and manipulation
import Foundation

let name = "Alice"
let score = 95.7

// String interpolation with expressions
print("Name: \(name), Score: \(score)")
print("Grade: \(score >= 90 ? "A" : "B")")
print("\(name.uppercased()) has \(name.count) characters")

// Number formatting
let amount = 1234567.89
let formatted = amount.formatted(.currency(code: "USD"))    // $1,234,567.89
let compact  = amount.formatted(.number.notation(.compactName))  // 1.2M
let percent  = 0.753.formatted(.percent.precision(.fractionLength(1)))  // 75.3%

// String methods
let text = "  Hello, Swift World!  "
print(text.trimmingCharacters(in: .whitespaces))   // "Hello, Swift World!"
print(text.components(separatedBy: ", "))           // ["  Hello", "Swift World!  "]
print("hello".capitalized)                          // "Hello"
print("hello world".split(separator: " ").map { $0.capitalized }.joined(separator: " "))  // "Hello World"

// Multi-line string literal
let json = """
{
    "name": "\(name)",
    "score": \(score)
}
"""

// String contains, prefix, suffix
let url = "https://thecodex.expert/coding/"
print(url.hasPrefix("https://"))  // true
print(url.hasSuffix("/"))         // true
print(url.contains("thecodex"))   // true
Swift referenceSwift overview · Learn Swift
← Kotlin All Snippets →
Everything Swift in one place — learning paths, reference, playground, and more. Swift Hub →