Common Collection Operations
In this page:
collection.count
collection.isEmpty
let copy = array.sorted() // new sorted array
array.sort() // sorts in place
array.first // Type? (optional)
array.last
array.reversed()
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
// Declare a constant `numbers`, set to `[5, 3, 8, 1]`
let numbers = [5, 3, 8, 1]
// Print "Count: \(numbers.count)" to the console
print("Count: \(numbers.count)")
// Print "Is empty: \(numbers.isEmpty)" to the console
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()
// Declare a constant `original`, set to `[5, 2, 8, 1]`
let original = [5, 2, 8, 1]
// Declare a constant `sortedCopy`, set to `original.sorted()`
let sortedCopy = original.sorted()
// Print "Original: \(original)" to the console
print("Original: \(original)")
// Print "Sorted copy: \(sortedCopy)" to the console
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
// Declare a constant `letters`, set to `["a", "b", "c"]`
let letters = ["a", "b", "c"]
// Print `letters.first as Any` to the console
print(letters.first as Any)
// Print `letters.last as Any` to the console
print(letters.last as Any)
// Print `Array(letters.reversed())` to the console
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: