How to sort an array | Swift Sort Array of Object by Property – Swift Quick Tips

Swift Programming

Difficulty: Beginner Easy | Normal | Advanced

Are you looking to learn how to sort Arrays in Swift? Well, look no further! Find out how you can sort Arrays in Swift, and learn how to sort a collection of objects by properties! This article explores the various methods and best practices for sorting Arrays, and the major differences between ‘sort’ and ‘sorted’ in Swift.

Within this article, we will cover the following:

  • Sorting arrays of simple data types
  • Sorting arrays of objects

Related topics in the series:

Sorting an Array

Swift offers built-in methods for sorting arrays. These methods are not only efficient but also easy to implement, making them the first go-to solution. Let’s explore how you can utilise these methods for basic array sorting tasks.

Sorting Arrays of Simple Data Types

When dealing with arrays of simple data types like integers or strings, Swift’s sort() and sorted() methods are incredibly useful. sort() modifies the original array, while sorted() returns a new array, keeping the original unaltered.

The following example shows how to use the sort() method to sort an array of strings and use .sorted() to return a new array of integers:

As seen in the example above the Array of Strings (fruits) is sorted alphabetically using sort(), and the Array of Integers are sorted into a new Array numerically using sorted().

Sorting Arrays of Objects

Sorting Arrays of Objects requires a bit more thought. You often need to sort these based on specific properties or custom criteria.

Swift’s powerful Closure syntax is useful here, allowing you to define exactly how your objects should be sorted.

Consider an array of Car objects, each with a make, year and colour property. To sort this Array by year, you could do the following:

The sorted() method takes a closure as its argument. The closure is used to compare two objects and return a Boolean value indicating whether the first object should be sorted before the second object. In this example, the closure compares the make property of two Car objects and returns true if the make property of the first object is less than the make property of the second object.

Conclusion

Leveraging Swift’s built-in methods and understanding the nuances of sorting different types of data, can help you write more efficient, readable, and maintainable code.

Remember, the key to sorting in Swift lies in choosing the right technique for the task at hand.

Thank you for reading

If you enjoyed this article feel free to share it 👍, alternatively you can catch me on my socials: