{

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


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

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

description is used to print an object when an objects is used for print to 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 Array of objects in Ascending Order

To sort an object isn ascending order, Provide compare method logic for sorted 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 an 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)
}
THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.