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?
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With