Swift – sort custom object array

Last Updated: April 14, 2020

We will see how we can sort the following array filled with products

First we will define the product class

class Product{
    var name : String
    var price : Float
    var qty : Int
    init( name : String, price: Float, qty: Int){
        self.name = name
        self.price = price
        self.qty = qty

Now we will create some products and fill to the array

var p1 = Product(name:"Micro USB Charging Cable ",price:8.99,qty:20)
var p2 = Product(name:"onn. 3-Piece Stylus Set",price:7.25,qty:12)
var p3 = Product(name:"Apple USB Power Adapter",price:17.00,qty:6)
var p4 = Product(name:"Onn 5W Wireless Charging Pad",price:3.99,qty:25)
var p5 = Product(name:"Anker Bluetooth Ultra-Slim Keyboard",price:8.8,qty:4)

var products: [Product] = []

If you want to sort the products according the product price you can use the following code

let sortedProducts = products.sorted(by: { $0.price > $1.price })

This will sort the array according to price

Now you can list the products

for p in sortedProducts{
    print(p.name + " " + String(p.price))

This method can be used to sort assenting or descending order