Custom Sorting an Array in Swift

Posted by

Let’s assume we have following Business struct

struct Business {
    let businessId: Int
    let rating: Int
}

And we have following data set for business with left value being businessId and right being rating

167 1
196 2
171 3
147 4
153 5
191 1
125 2
126 3
174 4
175 5
103 1
119 2
186 3
157 4
178 5
110 1
130 2
168 3
129 4
120 5

We should sort businesses in descending order of rating. For the businesses that have same rating, the original order of business should remain same.

To solve this, we can have following function:

func sortBusinesses(_ businesses: [Business]) -> [Business] {

    let set = NSOrderedSet(array: businesses)
    let newSet = set.sortedArray(comparator: { first, second -> ComparisonResult in
        let firstBusiness = first as! Business
        let secondBusiness = second as! Business
        if firstBusiness.rating == secondBusiness.rating {
            return .orderedSame
        }
        return .orderedDescending
    })
    return newSet as! [Business]

}

let sortedBusinesses = sortBusinesses(businesses)

The above will give us following output:

153 5
175 5
178 5
120 5
147 4
174 4
157 4
129 4
171 3
126 3
186 3
168 3
196 2
125 2
119 2
130 2
167 1
191 1
103 1
110 1

Here is gist for the example

// https://hashaam.com/2017/07/20/custom-sorting-an-array-in-swift/
struct Business {
let businessId: Int
let rating: Int
}
func sortBusinesses(_ businesses: [Business]) -> [Business] {
let set = NSOrderedSet(array: businesses)
let newSet = set.sortedArray(comparator: { first, second -> ComparisonResult in
let firstBusiness = first as! Business
let secondBusiness = second as! Business
if firstBusiness.rating == secondBusiness.rating {
return .orderedSame
}
return .orderedDescending
})
return newSet as! [Business]
}
let sortedBusinesses = sortBusinesses(businesses)

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s