Swift how to sort array of custom objects by property value

mohacs picture mohacs · Jun 10, 2014 · Viewed 372k times · Source

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?

Answer

Alex Wayne picture Alex Wayne · Jun 10, 2014

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