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?
With Swift 4,
Array
has two methods calledsorted()
andsorted(by:)
. The first method,sorted()
, has the following declaration:The second method,
sorted(by:)
, has the following declaration:1. Sort with ascending order for comparable objects
If the element type inside your collection conforms to
Comparable
protocol, you will be able to usesorted()
in order to sort your elements with ascending order. The following Playground code shows how to usesorted()
:2. Sort with descending order for comparable objects
If the element type inside your collection conforms to
Comparable
protocol, you will have to usesorted(by:)
in order to sort your elements with a descending order.3. Sort with ascending or descending order for non-comparable objects
If the element type inside your collection DOES NOT conform to
Comparable
protocol, you will have to usesorted(by:)
in order to sort your elements with ascending or descending order.Note that Swift also provides two methods called
sort()
andsort(by:)
as counterparts ofsorted()
andsorted(by:)
if you need to sort your collection in-place.If you are going to be sorting this array in more than one place, it may make sense to make your array type Comparable.
[Updated for Swift 3 with sort(by:)] This, exploiting a trailing closure:
where you use
<
or>
depending on ASC or DESC, respectively. If you want to modify theimages
array, then use the following:If you are going to do this repeatedly and prefer to define a function, one way is:
and then use as:
Swift 4.0, 4.1 & 4.2 First, I created mutable array of type imageFile() as shown below
Create mutable object image of type imageFile() and assign value to properties as shown below
Now, append this object to array arr
Now, assign the different properties to same mutable object i.e image
Now, again append image object to array arr
Now, we will apply Ascending order on fileId property in array arr objects. Use < symbol for Ascending order
Now, we will apply Descending order on on fileId property in array arr objects. Use > symbol for Descending order
In Swift 4.1. & 4.2 For sorted order use
If you want to sort original array of custom objects. Here is another way to do so in Swift 2.1
Where
id
is an Integer. You can use the same<
operator forString
properties as well.You can learn more about its use by looking at an example here: Swift2: Nearby Customers
Prints :
"["Peter", "Kweku", "Kofi", "Akosua", "Abena"]"