sorted() and contains()
In this page:
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:)
let numbers = [5, 2, 8, 1, 9]
let descending = numbers.sorted(by: >)
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
let names = ["Ann", "Bob", "Cara"]
print(names.contains("Bob"))
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: