Collections
8.1 Arrays
var numbers = [3, 1, 4, 1, 5] // [Int]
var empty: [String] = []
var zeros = Array(repeating: 0, count: 5)
numbers.append(9)
numbers += [2, 6]
numbers.insert(0, at: 0)
numbers.remove(at: 1)
numbers.removeLast()
numbers.removeAll { $0 == 1 }
print(numbers.count, numbers.isEmpty, numbers.first ?? 0, numbers.last ?? 0)
print(numbers[0], numbers[1...2], numbers.contains(4), numbers.firstIndex(of: 4) ?? -1)
numbers.sort() // in place
let sortedDesc = numbers.sorted(by: >)
numbers.reverse(); numbers.shuffle(); numbers.swapAt(0, 1)
let safe = numbers.indices.contains(10) ? numbers[10] : nil // avoid out-of-range crashes8.2 Higher-Order Functions
let nums = [1, 2, 3, 4, 5, 6]
nums.map { $0 * $0 } // [1, 4, 9, 16, 25, 36]
nums.filter { $0.isMultiple(of: 2) } // [2, 4, 6]
nums.reduce(0, +) // 21
nums.reduce(into: [Int: Int]()) { $0[$1 % 3, default: 0] += 1 }
["1", "x", "3"].compactMap(Int.init) // [1, 3]
[[1, 2], [3]].flatMap { $0 } // [1, 2, 3]
nums.first { $0 > 3 } // Optional(4)
nums.allSatisfy { $0 > 0 }; nums.contains { $0 > 5 }
nums.min(); nums.max(by: <)
nums.prefix(3); nums.suffix(2); nums.dropFirst(2); nums.dropLast()
nums.prefix(while: { $0 < 4 })
Dictionary(grouping: nums) { $0.isMultiple(of: 2) ? "even" : "odd" }
zip(["a", "b"], [1, 2]).map { "\($0)\($1)" } // ["a1", "b2"]
nums.split(whereSeparator: { $0 == 3 })
nums.chunks(ofCount: 2) // swift-algorithms package8.3 Sets
var colors: Set = ["red", "green", "blue"]
colors.insert("red") // no duplicates
colors.remove("green")
colors.contains("blue")
let a: Set = [1, 2, 3], b: Set = [3, 4]
a.union(b); a.intersection(b); a.subtracting(b); a.symmetricDifference(b)
a.isSubset(of: [1, 2, 3, 4]); a.isDisjoint(with: [9])8.4 Dictionaries
Dictionaries and Sets are unordered (use the swift-collections OrderedDictionary/OrderedSet, or sort them).
Keys must conform to Hashable.
var ages: [String: Int] = ["Ana": 30, "Bo": 25]
ages["Cy"] = 40 // add/update
ages["Bo"] = nil // remove
let anaAge = ages["Ana"] // Int? (the key may be missing)
let zedAge = ages["Zed", default: 0] // default value
ages["Ana", default: 0] += 1
ages.updateValue(31, forKey: "Ana")
for (name, age) in ages.sorted(by: { $0.key < $1.key }) { print(name, age) }
ages.keys; ages.values; ages.count
ages.mapValues { $0 + 1 }
ages.filter { $0.value > 26 }
ages.compactMapValues { $0 > 30 ? $0 : nil }
let merged = ages.merging(["Dee": 22]) { current, _ in current }
let fromPairs = Dictionary(uniqueKeysWithValues: [("a", 1), ("b", 2)])
let counts = Dictionary(["a", "b", "a"].map { ($0, 1) }, uniquingKeysWith: +)8.5 Value Semantics and Copy-on-Write
Arrays, Strings, Dictionaries, and Sets are value types with efficient copy-on-write.
var original = [1, 2, 3]
var copy = original // logically a copy; the storage is shared until mutation
copy.append(4) // copy-on-write: original is unaffected
print(original) // [1, 2, 3]