BeginnerLesson 5 of 16
Arrays, Dictionaries & Sets – Swift
The three collection types, with value semantics and bounds checking.
Array (ordered), Dictionary (key → value), and Set (unique, unordered). Whether a collection is mutable or not is decided solely by var or let.
var zahlen = [3, 1, 2]
zahlen.append(5)
zahlen.sort()
print(zahlen, zahlen[0], zahlen.last ?? 0, zahlen[1...2]) // [1, 2, 3, 5] 1 5 [2, 3]
zahlen.remove(at: 0)
zahlen.insert(9, at: 0)
print(zahlen, zahlen.count, zahlen.isEmpty) // [9, 2, 3, 5] 4 false
print(zahlen.contains(3), zahlen.firstIndex(of: 3) ?? -1) // true 2var person = ["name": "Ada", "stadt": "London"]
person["alter"] = "36" // add
print(person["email", default: "none"]) // none
print(person["name"] ?? "?") // Ada
person["stadt"] = nil // remove
for (schluessel, wert) in person.sorted(by: { $0.key < $1.key }) {
print(schluessel, wert) // alter 36 / name Ada
}
let a: Set = [1, 2, 3, 3]
let b: Set = [3, 4]
print(a.count, a.contains(2)) // 3 true
print(a.intersection(b), a.union(b).count) // [3] 4Collections have value semantics: an assignment logically copies (internally Swift uses copy-on-write, so the copy only really happens on modification). Changes to the copy do not affect the original.
var a1 = [1, 2]
var a2 = a1
a2.append(3)
print(a1, a2) // [1, 2] [1, 2, 3]
let leer: [String] = []
var index: [String: Int] = [:] // empty dictionary
index["a", default: 0] += 1
index["a", default: 0] += 1
print(index) // ["a": 2]TipAn access
dict[key] always returns an optional (Int?), because the key may be missing. Handy: dict[key, default: 0], which is good for counting and grouping.WarningAn index out of range (
zahlen[10] with 4 elements) is a runtime error (crash), not nil. Use first, last, indices.contains(i), or zahlen.indices instead of indexing blindly.