Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift how to sort array of custom objects by property value

lets say we have a custom class named imageFile and this class contains two properties.

class imageFile  {     var fileName = String()     var fileID = Int() } 

lots of them stored in Array

var images : Array = []  var aImage = imageFile() aImage.fileName = "image1.png" aImage.fileID = 101 images.append(aImage)  aImage = imageFile() aImage.fileName = "image1.png" aImage.fileID = 202 images.append(aImage) 

question is: how can i sort images array by 'fileID' ASC or DESC?

like image 202
modus Avatar asked Jun 09 '14 22:06

modus


People also ask

How do you sort an array of data in Swift?

Strings in Swift conform to the Comparable protocol, so the names are sorted in ascending order according to the less-than operator ( < ). To sort the elements of your collection in descending order, pass the greater-than operator ( > ) to the sort(by:) method. The sorting algorithm is not guaranteed to be stable.


1 Answers

First, declare your Array as a typed array so that you can call methods when you iterate:

var images : [imageFile] = [] 

Then you can simply do:

Swift 2

images.sorted({ $0.fileID > $1.fileID }) 

Swift 3+

images.sorted(by: { $0.fileID > $1.fileID }) 

The example above gives desc sort order

like image 186
Alex Wayne Avatar answered Sep 29 '22 21:09

Alex Wayne