Skip to content

Instantly share code, notes, and snippets.

@hashaam
Last active August 31, 2017 11:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hashaam/84f92768a80268629d844e7b71db3e91 to your computer and use it in GitHub Desktop.
Save hashaam/84f92768a80268629d844e7b71db3e91 to your computer and use it in GitHub Desktop.
Custom Sorting an Array in Swift
// 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)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment