← Back to Swift Course | Chapter 6: Collections | Lesson 4 of 7

Common Collection Operations

Collection operations are handy built-in tricks, like counting, sorting, or checking if something's inside, that work the same way across arrays, sets, and dictionaries.

count and isEmpty

These two properties work the same way across arrays, sets, and dictionaries, letting you check a collection's size without writing a loop.

Example: count and isEmpty

markup
let numbers = [5, 3, 8, 1]
print("Count: \(numbers.count)")
print("Is empty: \(numbers.isEmpty)")

sorted() vs sort()

.sorted() returns a brand-new sorted array leaving the original untouched, while .sort() sorts the array in place and requires it to be a var.

Example: sorted() vs sort()

markup
let original = [5, 2, 8, 1]
let sortedCopy = original.sorted()
print("Original: \(original)")
print("Sorted copy: \(sortedCopy)")

first, last, and reversed

.first and .last safely return optionals rather than crashing on empty collections, and .reversed() provides the elements in reverse order.

Example: first, last, and reversed

markup
let letters = ["a", "b", "c"]
print(letters.first as Any)
print(letters.last as Any)
print(Array(letters.reversed()))
Common Mistakes
  1. Writing a manual loop to check if a collection is empty instead of using the built-in .isEmpty property.
  2. Forgetting .count works on all collection types uniformly (arrays, sets, dictionaries, strings).
  3. Sorting an array with .sort() when you meant .sorted() -- one mutates in place, the other returns a new array.
Chapter Summary
  • .count and .isEmpty work consistently across arrays, sets, and dictionaries.
  • .sorted() returns a new sorted array without modifying the original; .sort() sorts in place.
  • .first and .last safely return optionals instead of crashing on an empty collection.
  • .reversed() returns elements in reverse order as a lazy sequence.
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.