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

sorted() and contains()

sorted() puts a list in order, and contains() tells you whether something you're looking for is actually in there.

Default Ascending Sort

Calling .sorted() on an array of comparable elements returns a new array arranged in ascending order.

Example: Default Ascending Sort

markup
let numbers = [5, 2, 8, 1, 9]
print(numbers.sorted())

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:)

markup
let numbers = [5, 2, 8, 1, 9]
let descending = numbers.sorted(by: >)
print(descending)

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

markup
let names = ["Ann", "Bob", "Cara"]
print(names.contains("Bob"))
print(names.contains(where: { $0.count > 3 }))
Common Mistakes
  1. Assuming .sorted() sorts in place; it always returns a new array, leaving the original unchanged.
  2. Using .contains() on a large array repeatedly in a loop when a Set would give faster membership checks.
  3. Forgetting .sorted(by:) lets you supply a custom comparison closure for descending order or custom criteria.
Chapter Summary
  • .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 a Bool.
  • .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:

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.