Getting everything ready for you…

Loading courses, problems and your progress. This takes just a moment.

0s

Swift Cheat Sheet

Basics

let x = 5; var y = 10
print("x = \(x)", terminator: "\n")
let n = Int(readLine()!)!
var name: String? = nil; name ?? "guest"; name?.count
if let n = name { } guard let n = name else { return }

Control flow

if a > b { } else { }
switch x { case 1, 2: break; case 3..<10: break; default: break }
for i in 0..<n { } for i in stride(from: n, to: 0, by: -1) { }
while cond { } repeat { } while cond

Collections

var a = [1, 2]; a.append(3); a.remove(at: 0); a.count; a.isEmpty
a.sorted(); a.map { $0 * 2 }; a.filter { $0 > 1 }; a.reduce(0, +)
var d = ["k": 1]; d["k"] = 2; d["z", default: 0]; d.keys.sorted()
var s: Set = [1, 2]; s.insert(3); s.contains(1)

Functions and closures

func add(_ a: Int, to b: Int = 0) -> Int { a + b }
let sq: (Int) -> Int = { $0 * $0 }
func run(_ f: @escaping () -> Void) { }

Types

struct P { var x: Int; mutating func move() { x += 1 } }
class A { init() {} }; class B: A { override init() { super.init() } }
enum E { case a, b(Int) }
protocol Named { var name: String { get } }
extension Int { var squared: Int { self * self } }

Errors and async

enum MyError: Error { case bad }
func f() throws { throw MyError.bad }
do { try f() } catch { print(error) }
func load() async throws -> Data { try await URLSession.shared.data(from: url).0 }

Full Swift documentation