Swift Collections
Swift provides three core collection types — arrays, sets, and dictionaries — each optimized for a different way of organizing and accessing data.
Arrays: ordered lists
An array stores values of the same type in a specific, ordered sequence, and the same value can appear more than once. Arrays are the default choice when order matters or when you need to access elements by numeric position.
Creating and modifying an array
var scores: [Int] = [88, 92, 79]
scores.append(95)
scores.insert(100, at: 0)
scores.remove(at: 2)
print(scores) // [100, 88, 95, 95] order depends on inserts
print("Count: \(scores.count)")
print("First: \(scores.first ?? 0)")Sets: unordered, unique values
A set stores distinct values of the same type with no defined ordering. Sets automatically discard duplicates and offer very fast membership testing, making them a good fit when you care whether something is present, not how many times or in what order.
Working with a Set
var tags: Set<String> = ["swift", "ios", "mobile"]
tags.insert("swift") // no effect, already present
tags.insert("apple")
print(tags.contains("ios")) // true
print("Tag count: \(tags.count)")
let other: Set<String> = ["ios", "android"]
print(tags.intersection(other)) // shared tagsDictionaries: key-value pairs
A dictionary stores associations between unique keys and values, with no defined ordering between pairs. Dictionaries excel at fast lookup by key, such as mapping usernames to profiles or country codes to country names.
Reading and updating a dictionary
var capitals: [String: String] = ["France": "Paris", "Japan": "Tokyo"]
capitals["Italy"] = "Rome"
if let capital = capitals["Japan"] {
print("The capital of Japan is \(capital)")
}
capitals["France"] = nil // removes the entry
print(capitals.keys.sorted())Choosing the right collection
- Use an Array when order matters and duplicates are allowed.
- Use a Set when you need uniqueness and fast 'contains' checks, and order doesn't matter.
- Use a Dictionary when you need to look values up by a unique key.
- All three are value types in Swift: assigning or passing one copies its contents, following copy-on-write semantics for performance.
Exercise: Swift Collections
Which statement about Swift Arrays is correct?