Swift Collection Methods

Arrays, dictionaries, and sets share a rich toolbox of built-in methods. These methods search, reorder, trim, and combine data without a single hand-written loop. Learning them turns ten lines of code into one.

Picture a kitchen drawer full of utensils. Each tool has one job: a peeler peels, a grater grates, and a whisk whisks. Collection methods work as utensils for data. Pick the right one and the job finishes quickly.

Diagram: The Toolbox

 Data:  ["Sunrise", "Ocean", "Midnight", "Breeze"]

 +-----------+---------------------------------------+
 | Question  | count, isEmpty, first, last           |
 | Search    | contains, firstIndex(of:)             |
 | Change    | append, insert, remove, removeAll     |
 | Reorder   | sorted, reversed, shuffled            |
 | Trim      | prefix, suffix, dropFirst, dropLast   |
 | Combine   | joined, zip, enumerated               |
 +-----------+---------------------------------------+

Questions About a Collection

var playlist = ["Sunrise", "Ocean", "Midnight", "Breeze"]

print(playlist.count)       // Output: 4
print(playlist.isEmpty)     // Output: false
print(playlist.first!)      // Output: Sunrise
print(playlist.last!)       // Output: Breeze

The properties first and last return optionals because an empty collection has neither. The example unwraps them with an exclamation mark only because the playlist holds songs.

Searching

print(playlist.contains("Ocean"))            // Output: true
print(playlist.firstIndex(of: "Midnight"))   // Output: Optional(2)
print(playlist.firstIndex(of: "Jazz"))       // Output: nil

Adding and Removing Items

playlist.append("Twilight")
playlist.insert("Intro", at: 0)
print(playlist)
// Output: ["Intro", "Sunrise", "Ocean", "Midnight", "Breeze", "Twilight"]

let removed = playlist.remove(at: 1)
print(removed)              // Output: Sunrise

playlist.removeLast()
print(playlist)
// Output: ["Intro", "Ocean", "Midnight", "Breeze"]

The remove(at:) method returns the item it removes. You can keep it or ignore it.

Sorting and Reordering

let numbers = [42, 7, 19, 3, 88]

print(numbers.sorted())                    // Output: [3, 7, 19, 42, 88]
print(numbers.sorted(by: >))               // Output: [88, 42, 19, 7, 3]
print(Array(numbers.reversed()))           // Output: [88, 3, 19, 7, 42]
print(numbers.min()!, numbers.max()!)      // Output: 3 88

The sorted() method returns a new array and leaves the original alone. The sort() method rearranges the original array in place.

Trimming a Collection

print(Array(playlist.prefix(2)))       // Output: ["Intro", "Ocean"]
print(Array(playlist.suffix(2)))       // Output: ["Midnight", "Breeze"]
print(Array(playlist.dropFirst()))     // Output: ["Ocean", "Midnight", "Breeze"]
print(Array(playlist.dropLast()))      // Output: ["Intro", "Ocean", "Midnight"]

Joining Items Into Text

print(playlist.joined(separator: " | "))
// Output: Intro | Ocean | Midnight | Breeze

Numbering Items With enumerated

for (position, song) in playlist.enumerated() {
    print("\(position + 1). \(song)")
}
// Output:
// 1. Intro
// 2. Ocean
// 3. Midnight
// 4. Breeze

Pairing Collections With zip

The zip function walks two collections together and builds pairs.

let names = ["Asha", "Ben", "Chen"]
let marks = [88, 92, 79]

for (name, mark) in zip(names, marks) {
    print("\(name) scored \(mark)")
}
// Output:
// Asha scored 88
// Ben scored 92
// Chen scored 79

Dictionary and Set Methods

Dictionaries offer keys, values, and removeValue(forKey:). Sets offer union, intersection, and subtracting.

let a: Set = [1, 2, 3, 4]
let b: Set = [3, 4, 5]

print(a.intersection(b).sorted())   // Output: [3, 4]
print(a.union(b).sorted())          // Output: [1, 2, 3, 4, 5]
print(a.subtracting(b).sorted())    // Output: [1, 2]

Choosing the Right Method

Many tasks have two possible tools: one that returns a new collection and one that changes the original. Methods with an ed or ing ending, such as sorted and reversed, leave the original untouched. Methods without that ending, such as sort and reverse, rewrite the original. Read the name closely and the behavior becomes predictable.

Constants declared with let reject mutating methods. Declare a collection with var when your code plans to add, remove, or reorder items.

Lightweight Views

Methods such as prefix, dropFirst, and reversed return lightweight views and avoid copying the data. Wrapping the result with Array(...) builds a real array. Large collections gain speed from this design.

Common Mistakes

Calling remove(at:) with a position beyond the end of the array crashes the program. Check isEmpty or compare the position with count before the call. Force unwrapping first on an empty array causes the same crash.

Modifying a collection while a loop walks through it creates confusing results. Build a new collection or loop over a copy.

Real-World Use

Music players use these methods to shuffle songs, show the top five tracks, and number the queue. Shopping apps use them to sort prices, remove sold-out items, and join product names into one summary line. A handful of well-known methods covers most daily tasks.

Practice Idea

Build a small to-do list with an array of strings. Add three tasks with append, move an urgent task to the top with insert, remove a finished task with remove(at:), and print the numbered list with enumerated. Ten minutes of practice locks these methods into memory far better than reading about them.

Try the same exercise with a dictionary of task names and due dates. Loop over the keys, sort them, and print each pair. The tools stay familiar across arrays, sets, and dictionaries, and that consistency is one of the best features of the Swift standard library.

Key Takeaways

  • Built-in methods replace many manual loops.
  • sorted() returns a new collection, while sort() changes the original.
  • prefix, suffix, dropFirst, and dropLast trim a collection.
  • enumerated and zip pair items with positions or with other collections.