How to Sort Array of objects in ascending and descending order in swift with example

This tutorial explains how to sort an array of objects with properties in ascending or descending order.

First, create a class and implements CustomStringConvertible, and provide an implementation for the description method.

The description is used to print an object when an object is used for print to the console.

import Foundation
class Employee  : CustomStringConvertible  {
    var id: Int;
    var name: String;
    var salary: Int =  0

    init ( _ id: Int, _ name:String, _ salary: Int){
        self.id=id
        self.name = name
        self.salary = salary

    }
   var description : String {
       return "id :\(id)  name \(name) salary \(salary)"
    }
}

Initialize an array of objects as given below

let employees = [Employee(11,"John",4000),Employee(21,"Mark",9000),Employee(10,"Dego",6000)]

Sort the Array of objects in Ascending Order

To sort an object in ascending order, Provide compare method logic for sorting as given below

    let employeesNameAsc = employees.sorted { (initial, next) -> Bool in
      return initial.name.compare(next.name) == .orderedAscending
    }

for employee in employeesNameAsc {
print(employee)
}

Sort Array of objects in Descending Order

sorted method is provided with compare logic for descending order

let employeesNameDesc = employees.sorted { (initial, next) -> Bool in
      return initial.name.compare(next.name) == .orderedDescending
    }
for employee in employeesNameDesc {
  print(employee)
}

Here is a complete example

import Foundation
class Employee  : CustomStringConvertible  {
    var id: Int;
    var name: String;
    var salary: Int =  0

    init ( _ id: Int, _ name:String, _ salary: Int){
        self.id=id
        self.name = name
        self.salary = salary

    }
   var description : String {
       return "id :\(id)  name \(name) salary \(salary)"
    }
}


let employees = [Employee(11,"John",4000),Employee(21,"Mark",9000),Employee(10,"Dego",6000)]
    let employeesNameAsc = employees.sorted { (initial, next) -> Bool in
      return initial.name.compare(next.name) == .orderedAscending
    }
for employee in employeesNameAsc {
  print(employee)
}
  let employeesNameDesc = employees.sorted { (initial, next) -> Bool in
      return initial.name.compare(next.name) == .orderedDescending
    }
for employee in employeesNameDesc {
  print(employee)
}