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.
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)]
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)
}
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)
}
🧮 Tags
Recent posts
Julia examples - Variable Type Nim example - Convert String to/from the Int How to get length of an array and sequence in Nim? Nim environment variables - read, set, delete, exists, and iterate examples? How to convert from single character to/from string in Nim?Related posts