Common Collection Operations
In this page:
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
let numbers = [5, 3, 8, 1]
print("Count: \(numbers.count)")
print("Is empty: \(numbers.isEmpty)")
Login to try C/C++/Java/PHP code in the editor
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()
let original = [5, 2, 8, 1]
let sortedCopy = original.sorted()
print("Original: \(original)")
print("Sorted copy: \(sortedCopy)")
Login to try C/C++/Java/PHP code in the editor
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
let letters = ["a", "b", "c"]
print(letters.first as Any)
print(letters.last as Any)
print(Array(letters.reversed()))
Login to try C/C++/Java/PHP code in the editor
- Writing a manual loop to check if a collection is empty instead of using the built-in
.isEmptyproperty. - Forgetting
.countworks on all collection types uniformly (arrays, sets, dictionaries, strings). - Sorting an array with
.sort()when you meant.sorted()-- one mutates in place, the other returns a new array.
.countand.isEmptywork consistently across arrays, sets, and dictionaries..sorted()returns a new sorted array without modifying the original;.sort()sorts in place..firstand.lastsafely 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: