SwSwift · Lesson 8 of 8

Swift Cheatsheet

Optionals, structs, enums, closures, and SwiftUI basics on one page.

Swift
// ── Basics ──────────────────────────────
let x = 42                 // constant (default choice)
var y = 3.14               // mutable
let name: String = "Ada"
print("Hi \(name), next: \(x + 1)")

// ── Optionals ───────────────────────────
var s: String? = nil
s?.count                   // safe chain -> nil
s ?? "default"             // nil-coalescing
if let s { print(s.count) }          // unwrap (shorthand)
guard let s else { return }          // unwrap or bail
// s! force-unwrap — avoid

// ── Control flow ────────────────────────
for i in 1...5 { }         // inclusive
for i in 0..<5 { }         // exclusive
while cond { }
switch grade {             // exhaustive, no fallthrough
case 90...100: "A"
case 80..<90:  "B"
case let g where g > 0: "C (\(g))"
default: "F"
}

// ── Functions & closures ────────────────
func greet(_ name: String, from city: String = "?") -> String {
    "Hi \(name) from \(city)"
}
greet("Ada", from: "London")
let double = { (n: Int) in n * 2 }
nums.map { $0 * 2 }        // $0 = first argument
Swift
// ── Structs & enums ─────────────────────
struct Student {
    let name: String
    var grade = 0
    var letter: String {                 // computed
        grade >= 90 ? "A" : "B"
    }
    mutating func improve() { grade += 1 }
}
// structs COPY on assignment; classes share references

enum Result {
    case success(data: String)
    case failure(code: Int)
}
switch r {
case .success(let data): print(data)
case .failure(let code): print(code)
}

protocol Describable { var description: String { get } }
extension Student: Describable {
    var description: String { "\(name): \(grade)" }
}

// ── Collections ─────────────────────────
var nums = [3, 1, 4]; nums.append(1)
var ages = ["Ada": 17]; ages["Ada"]     // -> Int?
let set: Set = [1, 2, 3]
nums.filter { $0 > 1 }.map { $0 * 2 }.sorted()
nums.reduce(0, +); nums.max(); nums.contains(4)

// ── Errors & async ──────────────────────
enum AppError: Error { case notFound }
func load() throws -> String { throw AppError.notFound }
do { let d = try load() } catch { print(error) }
let maybe = try? load()               // nil on failure

func fetch() async throws -> Data {
    let (data, _) = try await URLSession.shared
        .data(from: url)
    return data
}
async let a = fetch(); async let b = fetch()  // concurrent
let both = try await (a, b)

// ── SwiftUI skeleton ────────────────────
struct ContentView: View {
    @State private var count = 0
    var body: some View {
        VStack {
            Text("Count: \(count)")
            Button("Tap") { count += 1 }
        }
    }
}