sorted() and contains()
In this page:
let ascending = array.sorted()
let custom = array.sorted(by: { a, b in a > b })
array.contains(value)
array.contains(where: { condition using $0 })
Default Ascending Sort
Calling .sorted() on an array of comparable elements returns a new array arranged in ascending order.
Example: Default Ascending Sort
let numbers = [5, 2, 8, 1, 9]
print(numbers.sorted())
Login to try C/C++/Java/PHP code in the editor
Custom Sorting with sorted(by:)
Passing a closure to .sorted(by:) lets you define exactly how two elements should be compared, such as sorting in descending order.
Example: Custom Sorting with sorted(by:)
// Declare a constant `numbers`, set to `[5, 2, 8, 1, 9]`
let numbers = [5, 2, 8, 1, 9]
// Declare a constant `descending`, set to `numbers.sorted(by: >)`
let descending = numbers.sorted(by: >)
// Print `descending` to the console
print(descending)
Login to try C/C++/Java/PHP code in the editor
Checking Membership with contains
.contains() checks whether a specific value exists in a collection, and .contains(where:) checks for any element satisfying a custom condition.
Example: Checking Membership with contains
// Declare a constant `names`, set to `["Ann", "Bob", "Cara"]`
let names = ["Ann", "Bob", "Cara"]
// Print `names.contains("Bob")` to the console
print(names.contains("Bob"))
// Print `names.contains(where: { $0.count > 3 })` to the console
print(names.contains(where: { $0.count > 3 }))
Login to try C/C++/Java/PHP code in the editor
- Assuming
.sorted()sorts in place; it always returns a new array, leaving the original unchanged. - Using
.contains()on a large array repeatedly in a loop when aSetwould give faster membership checks. - Forgetting
.sorted(by:)lets you supply a custom comparison closure for descending order or custom criteria.
.sorted()returns a new array in ascending order by default for comparable elements..sorted(by:)accepts a closure to define custom ordering, such as descending or by a specific property..contains()checks whether a collection includes a given element, returning aBool..contains(where:)checks for an element matching a custom condition instead of exact equality.
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: