Jera Docs

Documents, reminders and "cheat sheets" I use in everyday development

View the Project on GitHub jeradesign/jeradoc

Swift Cheat Sheet

Strings

let actor = "Denzel Washington"
let filename = "paris.jpg"
let result = "⭐️ You win! ⭐️"

let quote = "Then he tapped a sign saying \"Believe\" and walked away."

let movie = """
    A day in
    the life of an
    Apple engineer
    """ // whitespace ahead of lines trimmed to here

actor.count // 17

result.uppercased() // "⭐️ YOU WIN! ⭐️"
movie.hasPrefix("a day") // false -- case matters!
filename.hasSuffix(".jpg") // true

string.components(separatedBy: "\n")
string.trimmingCharacters(in: .whitespacesAndNewlines)

Arrays

var presidents = ["Washington", "Adams", "Jefferson", "Madison", "Monroe", "Adams"]

Transforming (non-mutating)

map(_:) // from Sequence
flatMap(_:) // append elements of returned sequences individually
compactMap() // non-nil returned elements only
reduce(_:_:) // closure returns a new result object
reduce(into:_:) // closure mutates inout result object
lazy:

Reordering

Mutating Non-Mutating
sort(by:) sorted(by:)
reverse() reversed()
shuffle(using:) shuffled(using:)
partition(by:)  
swapAt(,)  

Splitting and Joining

split(separator:maxSplits:omittingEmptySubsequences:)
split(maxSplits:omittingEmptySubsequences:whereSeparator) // closure
joined(separator:)

Differences

difference(from:by:)
applying()

print(presidents.count)
print(presidents.sorted())
presidents.remove(at: 5)
print(presidents)
print(presidents.contains("Washington"))
print(presidents.contains("Hubbard"))
print(presidents.reversed())
presidents.sort()
presidents.reverse()
presidents.randomElement() ?? "Empty string"
presidents.removeFirst()
presidents.removeLast()
presidents.popLast() -> Element?

Two-Dimensional Arrays

var a = Array(repeating: Array(repeating: 0, count: 8), count: 8)

Dictionaries

let employee2 = [
    "name": "Taylor Swift",
    "job": "Singer",
    "location": "Nashville" ]

print(employee2["name"]) // Optional("Taylor Swift")
print(employee2["job"] ?? "Unknown")
print(employee2["location"])
print(employee2["password"]) // nil
print(employee2["favorite color"] ?? "Unknown") // Unknown
print(employee2["favorite color", default: "red"]) // red

let names = [true: "true", false: "false"]

print(names[true])

print(employee2["favorite ice cream flavor", default: "Vanilla"])

Tuples

func getUser() -> (firstName: String, lastName: String) {
    ("Taylor", "Swift")
}

Closures

Structs

var computedProperty: Type {
    /* compute value */
}

var computedProperty: Type {
    get {
        /* compute value */
    }
    set {
        /* mutate stuff */
    }
}

var propertyObservers: Type {
    willSet {
        print(newValue)
    }
    didSet {
        print(oldValue)
    }
}

Access Control

Static Properties and Methods

Classes

Differences from Struct

Protocols

struct User: Equatable { // Swift automatically writes piecewise equality test
    let name: String
}

Extensions

extension Numeric {
    func squared() -> Self {
        self * self
    }
}

Optionals

let theyMightBeGiants: [Giant?]
let wereCertainlyDwarfs: [Dwarf]

Nil Coalescing Operator

optional ?? valueIfNil

Optional Chaining

let author2 = book2?.author?.first?.uppercased() ?? "A"

Optional in Lieu of Do/Try/Catch

let user = (try? getUser(id: 23)) ?? "Error"

Generics

func identity<A>(_ value: A) -> A {
    return value
}

enum Optional<Wrapped> {
    case none
    case some(Wrapped)
}

Logging

let log = Logger(subsystem: "com.josh.example", category: "error")

Value Types

struct MyValueType: Codable, Sendable, Identifiable, Hashable {}

Dates

DateComponents

Serialization

MyClass: Codable { }
    enum CodingKeys: String, CodingKey { }

if let encoded = try? JSONEncoder().encode(object) { }
if let decodedObject = try? JSONDecoder().decode(DecodedObjectType.self, from: encoded) { }

Loading Data

let (data, _) = try await URLSession.shared.data(from: url)
let recentChangesResponse = try JSONDecoder().decode(RecentChangesResponse.self, from: data)
recentChanges = recentChangesResponse.query.recentchanges

Concurrency

SwiftData

@Model class ModelClass {
WindowGroup {
    ContentView()
}
.modelContainer(for: ModelClass.self)
#Preview {
    do {
        let config = ModelConfiguration(isStoredInMemoryOnly: true)
        let container = try ModelContainer(for: User.self, configurations: config)
        let user = User(name: "Taylor Swift", city: "Nashville", joinDate: .now)
        return EditUserView(user: user)
            .modelContainer(container)
    } catch {
        return Text("Failed to create container: \(error.localizedDescription)")
    }
}

Core Image

import CoreImage.CIFilterBuiltins