Swift Tutorials: `sorted(by:)` with Closure

beginner
9 min

Swift Tutorials: sorted(by:) with Closure

Welcome to another enlightening tutorial on CodeYourCraft! Today, we're diving into the fascinating world of Swift, exploring the powerful sorted(by:) function that leverages Closures for sorting arrays. Let's dive right in! šŸŽÆ

Understanding the Basics

Before we delve into sorted(by:), let's refresh our memory with some essential Swift concepts:

  1. Arrays: A collection of elements of the same type, ordered and changeable.
  2. Closures: Self-contained blocks of functionality that can be passed around and used in your code.

Sorting Arrays with sorted(by:)

Now that we have the basics covered, let's dive into the sorted(by:) function. This function sorts an array using a given closure as the sorting criteria. šŸ’” Pro Tip: The sorted(by:) function returns a new sorted array, leaving the original array unchanged.

The sorted(by:) Syntax

Here's the basic syntax for using sorted(by:):

swift
array.sorted(by: someComparator)
  • array: The array to be sorted.
  • someComparator: A closure that takes two elements and returns a Bool indicating whether the first element should sort before the second.

Writing a Comparator Closure

To create a custom comparator, you'll need to write a closure that conforms to the Comparable protocol. The closure should take two elements of the same type and return a Bool.

swift
func compareByAge(_ a: Person, _ b: Person) -> Bool { return a.age > b.age // or a.age < b.age for descending order } let people = [ Person(name: "Alice", age: 25), Person(name: "Bob", age: 30), Person(name: "Charlie", age: 20) ] let sortedPeople = people.sorted(by: compareByAge)

šŸ“ Note: In this example, we've created a Person struct and defined a comparator function compareByAge to sort people by age.

Advanced Sorting with sorted(by:)

The power of sorted(by:) lies in its ability to handle complex sorting scenarios. For example, let's say we want to sort people by age, but if two people have the same age, we want to sort them by name. We can achieve this using a combined comparator closure:

swift
func compareByAgeThenName(_ a: Person, _ b: Person) -> Bool { if a.age == b.age { return a.name < b.name } return a.age > b.age } let sortedPeople = people.sorted(by: compareByAgeThenName)

Practice Time!

Now that you've learned how to use sorted(by:) with Closures, let's test your understanding with a quick quiz:

Quick Quiz
Question 1 of 1

Which function does Swift provide for sorting arrays using a custom comparator?

Happy coding! šŸ’”šŸŽÆ