# Multi-Criteria Array Sorting in Swift

Example of sorting Player structs by score, name and ID

- **Source:** [Augmented Code](https://brifing.si/source/9d6dc00a-03c0-43e1-80cc-345c746dc352)
- **Published:** 2024-10-07
- **Topic:** [Software & Engineering](https://brifing.si/c/engineering)
- **Original article:** <https://augmentedcode.io/2024/10/07/sorting-arrays-in-swift-multi-criteria/>
- **On Brifing:** https://brifing.si/s/b6246623-4924-4839-9243-76701c7297a5

## Basic Sorting in Swift

Swift's Foundation library provides the sorted(by:) function for array sorting. The areInIncreasingOrder closure returns true if the first parameter should precede the second. This basic mechanism suffices for single-criterion sorting operations.

## Need for Multiple Criteria

Real-world scenarios often require sorting by multiple properties. For example, we might want to sort a player list first by score, then by name, and finally by ID. This requires implementing a cascading comparison logic within the closure.

## Player Struct Example

The Player struct used in the article has id, name and score properties. The sample array contains 7 different players. Some share identical scores or names, demonstrating the importance of multi-criteria sorting.

## Implementing Sorting Logic

First compare scores (descending). If equal, compare names case-insensitively (A-Z). If names match, sort by ID (ascending). This logic is implemented using nested if blocks within the sorting closure.

## String Comparison Technique

Name comparison uses Foundation's localizedCaseInsensitiveCompare method. This approach provides consistent sorting by ignoring case sensitivity, returning .orderedAscending, .orderedSame or .orderedDescending results.

## Output and Practical Importance

The sorted output shows Nora with the highest score first. April and John with equal scores are ordered alphabetically. Multi-criteria sorting is crucial for meaningful data organization in applications.

## Sources covering this story

- https://augmentedcode.io/2024/10/07/sorting-arrays-in-swift-multi-criteria/ — 

---

_Summary written by Brifing from the original reporting. Copyright in the original article belongs to its publisher; read the full piece at the link above._
