Swift Cheat Sheet: Syntax, Collections, Optionals, Protocols and Concurrency at a Glance

Swift 30 min min read Updated: Nov 21, 2026 Beginner
Swift Cheat Sheet: Syntax, Collections, Optionals, Protocols and Concurrency at a Glance
Beginner Topic 3 of 3

Variables and Types

swift let name = "Swift" var count = 3 let pi: Double = 3.14 print("\(name) \(count) \(pi)")
Output

Swift 3 3.14

Collections

swift var arr = [3, 1, 2] arr.append(4) let dict = ["a": 1, "b": 2] let set: Set = [1, 2, 2] print(arr.sorted(), dict["a"] ?? 0, set.count)
Output

[1, 2, 3, 4] 1 2

Optionals

swift let text: String? = "5" if let t = text, let n = Int(t) { print(n) } print(text?.count ?? 0)
Output

5 | 1

Control Flow and Functions

swift func grade(_ s: Int) -> String { switch s { case 90...: return "A" case 75..<90: return "B" default: return "C" } } for i in 1...3 { print(i, grade(70 + i * 7)) }
Output

1 B | 2 B | 3 A

Structs, Enums and Protocols

swift protocol Named { var name: String { get } } struct Dog: Named { var name: String } enum Shape { case circle(Double), square(Double) } func area(_ s: Shape) -> Double { switch s { case .circle(let r): return 3.14 * r * r case .square(let a): return a * a } } print(Dog(name: "Rex").name, area(.square(3)))
Output

Rex 9.0

Errors and Closures

swift enum E: Error { case bad } func risky(_ x: Int) throws -> Int { if x < 0 { throw E.bad }; return x } print((try? risky(-1)) as Any, try risky(2)) print([1, 2, 3, 4].filter { $0 % 2 == 0 }.map { $0 * 10 }.reduce(0, +))
Output

nil 2 | 60

Generics

swift func largest<T: Comparable>(_ a: [T]) -> T? { a.max() } print(largest([3, 9, 4]) as Any, largest(["a", "c"]) as Any)
Output

Optional(9) Optional("c")

Concurrency

swift func work(_ n: Int) async -> Int { n * 2 } async let a = work(1) async let b = work(2) print(await a + b) actor Bank { var total = 0; func add(_ n: Int) { total += n } } let bank = Bank() await bank.add(5) print(await bank.total)
Output

6 | 5

Handy Reminders

TopicRemember
let vs varPrefer let
struct vs classValue vs reference
guardEarly exit, flat code
weakBreak retain cycles
awaitPossible suspension point
actorProtects shared state

Conclusion

Keep this page handy while you practice, and look up details in the lessons.

Quick Summary: Swift syntax quick reference.

Get Newsletter

Subscibe to our newsletter and we will notify you about the newest updates on Edugators