Swift Cheat Sheet: Syntax, Collections, Optionals, Protocols and Concurrency at a Glance
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
| Topic | Remember |
|---|---|
| let vs var | Prefer let |
| struct vs class | Value vs reference |
| guard | Early exit, flat code |
| weak | Break retain cycles |
| await | Possible suspension point |
| actor | Protects shared state |
Conclusion
Keep this page handy while you practice, and look up details in the lessons.
Quick Summary: Swift syntax quick reference.

