Collections: Array, Dictionary and Set
Array
swift
var names = ["Asha", "Ravi", "Meena"]
names.append("Kabir")
names.insert("Zoya", at: 0)
names.remove(at: 1)
print(names.count) // 4
print(names[0]) // Zoya
print(names.first ?? "none")
print(names.last ?? "none")
print(names.contains("Asha")) // true
print(names.isEmpty)
Careful:
names[10] on a short array crashes the app. Check names.indices.contains(10) or use first and last which return optionals.
Array Methods
swift
let nums = [5, 3, 8, 1]
print(nums.sorted()) // [1, 3, 5, 8]
print(nums.sorted(by: >)) // [8, 5, 3, 1]
print(nums.max() ?? 0) // 8
print(nums.filter { $0 > 3 }) // [5, 8]
print(nums.map { "N\($0)" }) // ["N5", "N3", "N8", "N1"]
print(nums.firstIndex(of: 8) ?? -1) // 2
print(nums.contains { $0 > 7 }) // true
print(Array(nums.prefix(2))) // [5, 3]
Dictionary
A dictionary stores values by key.
swift
var ages = ["Asha": 25, "Ravi": 30]
ages["Meena"] = 28 // add or change
ages["Ravi"] = nil // remove
if let age = ages["Asha"] { // lookup returns an Optional
print(age)
}
let safe = ages["Unknown", default: 0] // default value
for (name, age) in ages {
print("\(name): \(age)")
}
print(ages.keys.sorted())
Set
A set holds unique items in no particular order and checks membership very quickly.
swift
var tags: Set = ["swift", "ios", "swift"]
print(tags.count) // 2
tags.insert("xcode")
print(tags.contains("ios")) // true
let a: Set = [1, 2, 3]
let b: Set = [3, 4]
print(a.union(b)) // {1, 2, 3, 4}
print(a.intersection(b)) // {3}
| Collection | Ordered? | Duplicates? | Access |
|---|---|---|---|
| Array | Yes | Allowed | Index |
| Dictionary | No | Keys unique | Key |
| Set | No | No | Value |
Useful Extras
swift
let words = ["apple", "avocado", "banana"]
let grouped = Dictionary(grouping: words) { $0.first! }
print(grouped) // ["a": ["apple", "avocado"], "b": ["banana"]]
let total = [1, 2, 3].reduce(0, +) // 6
let pairs = zip([1, 2], ["a", "b"]).map { "\($0)\($1)" }
SwiftUI link: Arrays of data are what
List and ForEach display. Master arrays, map and filter and building lists in SwiftUI will feel easy.
Conclusion
Arrays, dictionaries and sets cover nearly all data needs. Remember that out-of-range access crashes, and dictionary lookups return optionals.
Quick Summary: Array is ordered, Dictionary uses keys and Set is unique. Use map, filter, sorted and reduce to transform data.

