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?
You can also do something like
so your images array will be stored as sorted
If you are not using custom objects, but value types instead that implements Comparable protocol (Int, String etc..) you can simply do this:
An example:
Two alternatives
1) Ordering the original array with sortInPlace
2) Using an alternative array to store the ordered array
First, declare your Array as a typed array so that you can call methods when you iterate:
Then you can simply do:
Swift 2
Swift 3 & 4
The example above gives desc sort order
Swift 2 through 4
The original answer sought to sort an array of custom objects using some property. Below I will show you a few handy ways to do this same behavior w/ swift data structures!
Little things outta the way, I changed ImageFile ever so slightly. With that in mind, I create an array with three image files. Notice that metadata is an optional value, passing in nil as a parameter is expected.
ImageFile has a property named size. For the following examples I will show you how to use sort operations w/ properties like size.
smallest to biggest size (<)
biggest to smallest (>)
Next we'll sort using the String property name. In the same manner, use sort to compare strings. But notice the inner block returns a comparison result. This result will define sort.
A-Z (.orderedAscending)
Z-A (.orderedDescending)
Next is my favorite way to sort, in many cases one will have optional properties. Now don't worry, we're going to sort in the same manner as above except we have to handle nil! In production;
I used this code to force all instances in my array with nil property values to be last. Then order metadata using the assumed unwrapped values.
It is possible to have a secondary sort for optionals. For example; one could show images with metadata and ordered by size.
Swift 3