Swift Cheatsheet

Collections

Use this Swift reference while you build software engineering projects, review code for technical interview prep, or polish examples for a software engineer resume.

Arrays

var nums = [3, 1, 4]
var empty: [Int] = []
let zeros = Array(repeating: 0, count: 5)
var grid = Array(repeating: Array(repeating: 0, count: cols), count: rows)

nums.append(1)                   // amortized O(1)
nums.insert(9, at: 0)            // O(n)
nums.remove(at: 2)               // O(n), returns the removed element
nums.removeLast()                // O(1)
nums += [5, 9]

nums.count
nums.isEmpty
nums.first                       // Optional, safe on empty
nums.last
nums[0]                          // crashes if out of bounds
nums.contains(4)                 // O(n)
nums.first(where: { $0 > 3 })    // first match, Optional
nums.firstIndex(of: 4)           // Int?
nums.allSatisfy { $0 > 0 }
nums.min()
nums.max()

Transformations

let nums = [3, 1, 4, 1, 5]

nums.map { $0 * $0 }                       // [9, 1, 16, 1, 25]
nums.filter { $0 > 1 }                     // [3, 4, 5]
nums.reduce(0, +)                          // 14
nums.reduce(into: [:]) { acc, n in acc[n, default: 0] += 1 }   // frequency map
nums.sorted()                              // ascending copy
nums.sorted(by: >)                         // descending
Array(nums.reversed())
Array(nums.prefix(2))                      // [3, 1]
Array(nums.suffix(2))                      // [1, 5]
Array(zip(names, scores))                  // pairs, stops at the shorter one

let flat = [[1, 2], [3]].flatMap { $0 }            // [1, 2, 3]
let ints = ["1", "x", "3"].compactMap(Int.init)    // [1, 3]

Dictionaries

var counts: [String: Int] = [:]
counts["swift", default: 0] += 1       // upsert idiom
counts["kotlin"] = 2
counts["kotlin"] = nil                 // removes the key
let n = counts["swift"] ?? 0           // lookups return Optional

for (key, value) in counts { print(key, value) }
for key in counts.keys.sorted() { print(key, counts[key]!) }

counts.mapValues { $0 * 10 }
counts.filter { $0.value > 1 }
let byLength = Dictionary(grouping: words, by: \.count)   // [Int: [String]]
let merged = a.merging(b) { current, _ in current }       // resolve key clashes

Dictionary iteration order is unspecified. Sort the keys when output order matters.

Sets

var seen: Set<Int> = [1, 2, 3]
seen.insert(4)                   // returns (inserted: Bool, memberAfterInsert:)
seen.remove(2)
seen.contains(3)                 // O(1) average, vs O(n) on Array

let a: Set = [1, 2, 3]
let b: Set = [3, 4]
a.union(b)                       // {1, 2, 3, 4}
a.intersection(b)                // {3}
a.subtracting(b)                 // {1, 2}
a.symmetricDifference(b)         // {1, 2, 4}
a.isSubset(of: b)
a.isSuperset(of: b)
a.isDisjoint(with: b)

Elements must be Hashable (all standard scalar and string types are, and structs can synthesize it).

Stacks, queues, and heaps

// Stack: Array is ideal
var stack = [Int]()
stack.append(1)
let top = stack.popLast()        // Optional, O(1)

// Queue: removeFirst() is O(n). Keep a head index instead.
var queue = [Int]()
var head = 0
queue.append(1)
let front = queue[head]
head += 1

// Heap and Deque come from the swift-collections package
// import Collections
// var heap = Heap([5, 1, 3])
// heap.popMin()
// var deque = Deque([1, 2, 3])
// deque.popFirst()              // O(1)

Slices

let xs = [10, 20, 30, 40]
let slice = xs[1...2]            // ArraySlice, shares storage
slice.startIndex                 // 1, slices keep the parent's indices
let copy = Array(slice)          // reindexes from 0
xs[2...]                         // one-sided ranges slice too
xs[..<2]

Slices are O(1) views. Convert to Array before storing long-term or doing 0-based index math.