We can easily sort a swift array using two provided function
array.sort
array.sorted
We will see both array.sort() and array.sorted() in action and will understand how they differ from each other in a subtle way, while sorting a swift array in place and returning a sorted copy of the swift array.
Example code for the playground for the swift array
The example code given below defines a student struct and creates an array of students which we will sort.
struct Student { var name:String var age:Int } var students = [ Student(name: "A", age: 20), Student(name: "B", age: 10), Student(name: "C", age: 12), Student(name: "D", age: 8), Student(name: "E", age: 23), Student(name: "F", age: 29), Student(name: "G", age: 30), Student(name: "H", age: 11) ]
As you can see the array contains students with their age in random order.
Returning a sorted swift array
First, we will sort the student
array and return its copy, without actually sorting the students
array. We will use array.sorted()
let arry = students.sorted { return $0.age < $1.age }
No print the array
arry.forEach{ print("\($0.name)======\($0.age)") }
The output will be students sorted by their age.
// student sorted by age D======8 B======10 H======11 C======12 A======20 E======23 F======29 G======30
But if we go and print the original students
array. We will see that the order is still the same as at the time of creation. So array.sorted()
has not actually sorted the students
array but has returned a sorted copy
students.forEach{ print("\($0.name)======\($0.age)") } //output A======20 B======10 C======12 D======8 E======23 F======29 G======30 H======11
Sorting a swift array in place
This time we will sort the swift array in place which means the content of the original students
array will be sorted. we will use array.sort()
function.
// sort students array students.sort { return $0.age < $1.age } print students array students.forEach{ print("\($0.name)======\($0.age)") }
Now this time the contents of students
array has been sorted
D======8 B======10 H======11 C======12 A======20 E======23 F======29 G======30
Hope this helps !!!!