← 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.
Syntax
swift
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

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

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
// 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 }))
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
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.