Swift how to sort array of custom objects by property value

ArraysSortingSwift

Arrays Problem Overview


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?

Arrays Solutions


Solution 1 - Arrays

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 the results in descending order.

Solution 2 - Arrays

[Updated for Swift 3 with sort(by:)] This, exploiting a trailing closure:

images.sorted { $0.fileID < $1.fileID }

where you use < or > depending on ASC or DESC, respectively. If you want to modify the images array, then use the following:

images.sort { $0.fileID < $1.fileID }

If you are going to do this repeatedly and prefer to define a function, one way is:

func sorterForFileIDASC(this:imageFile, that:imageFile) -> Bool {
  return this.fileID < that.fileID
}

and then use as:

images.sort(by: sorterForFileIDASC)

Solution 3 - Arrays

Swift 3

people = people.sorted(by: { $0.email > $1.email })

Solution 4 - Arrays

Nearly everyone gives how directly, let me show the evolvement:

you can use the instance methods of Array:

// general form of closure
images.sortInPlace({ (image1: imageFile, image2: imageFile) -> Bool in return image1.fileID > image2.fileID })

// types of closure's parameters and return value can be inferred by Swift, so they are omitted along with the return arrow (->)
images.sortInPlace({ image1, image2 in return image1.fileID > image2.fileID })

// Single-expression closures can implicitly return the result of their single expression by omitting the "return" keyword
images.sortInPlace({ image1, image2 in image1.fileID > image2.fileID })

// closure's argument list along with "in" keyword can be omitted, $0, $1, $2, and so on are used to refer the closure's first, second, third arguments and so on
images.sortInPlace({ $0.fileID > $1.fileID })

// the simplification of the closure is the same
images = images.sort({ (image1: imageFile, image2: imageFile) -> Bool in return image1.fileID > image2.fileID })
images = images.sort({ image1, image2 in return image1.fileID > image2.fileID })
images = images.sort({ image1, image2 in image1.fileID > image2.fileID })
images = images.sort({ $0.fileID > $1.fileID })

For elaborate explanation about the working principle of sort, see The Sorted Function.

Solution 5 - Arrays

With Swift 5, Array has two methods called sorted() and sorted(by:). The first method, sorted(), has the following declaration:

>Returns the elements of the collection, sorted.

func sorted() -> [Element]

The second method, sorted(by:), has the following declaration:

>Returns the elements of the collection, sorted using the given predicate as the comparison between elements.

func sorted(by areInIncreasingOrder: (Element, Element) throws -> Bool) rethrows -> [Element]

#1. Sort with ascending order for comparable objects

If the element type inside your collection conforms to Comparable protocol, you will be able to use sorted() in order to sort your elements with ascending order. The following Playground code shows how to use sorted():

class ImageFile: CustomStringConvertible, Comparable {
    
    let fileName: String
    let fileID: Int
    var description: String { return "ImageFile with ID: \(fileID)" }
    
    init(fileName: String, fileID: Int) {
        self.fileName = fileName
        self.fileID = fileID
    }
    
    static func ==(lhs: ImageFile, rhs: ImageFile) -> Bool {
        return lhs.fileID == rhs.fileID
    }
    
    static func <(lhs: ImageFile, rhs: ImageFile) -> Bool {
        return lhs.fileID < rhs.fileID
    }
    
}

let images = [
    ImageFile(fileName: "Car", fileID: 300),
    ImageFile(fileName: "Boat", fileID: 100),
    ImageFile(fileName: "Plane", fileID: 200)
]

let sortedImages = images.sorted()
print(sortedImages)

/*
 prints: [ImageFile with ID: 100, ImageFile with ID: 200, ImageFile with ID: 300]
 */

#2. Sort with descending order for comparable objects

If the element type inside your collection conforms to Comparable protocol, you will have to use sorted(by:) in order to sort your elements with a descending order.

class ImageFile: CustomStringConvertible, Comparable {
    
    let fileName: String
    let fileID: Int
    var description: String { return "ImageFile with ID: \(fileID)" }
    
    init(fileName: String, fileID: Int) {
        self.fileName = fileName
        self.fileID = fileID
    }

    static func ==(lhs: ImageFile, rhs: ImageFile) -> Bool {
        return lhs.fileID == rhs.fileID
    }
    
    static func <(lhs: ImageFile, rhs: ImageFile) -> Bool {
        return lhs.fileID < rhs.fileID
    }

}

let images = [
    ImageFile(fileName: "Car", fileID: 300),
    ImageFile(fileName: "Boat", fileID: 100),
    ImageFile(fileName: "Plane", fileID: 200)
]

let sortedImages = images.sorted(by: { (img0: ImageFile, img1: ImageFile) -> Bool in
    return img0 > img1
})
//let sortedImages = images.sorted(by: >) // also works
//let sortedImages = images.sorted { $0 > $1 } // also works
print(sortedImages)

/*
 prints: [ImageFile with ID: 300, ImageFile with ID: 200, ImageFile with ID: 100]
 */

#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 use sorted(by:) in order to sort your elements with ascending or descending order.

class ImageFile: CustomStringConvertible {
    
    let fileName: String
    let fileID: Int
    var description: String { return "ImageFile with ID: \(fileID)" }
    
    init(fileName: String, fileID: Int) {
        self.fileName = fileName
        self.fileID = fileID
    }
    
}

let images = [
    ImageFile(fileName: "Car", fileID: 300),
    ImageFile(fileName: "Boat", fileID: 100),
    ImageFile(fileName: "Plane", fileID: 200)
]

let sortedImages = images.sorted(by: { (img0: ImageFile, img1: ImageFile) -> Bool in
    return img0.fileID < img1.fileID
})
//let sortedImages = images.sorted { $0.fileID < $1.fileID } // also works
print(sortedImages)

/*
 prints: [ImageFile with ID: 300, ImageFile with ID: 200, ImageFile with ID: 100]
 */

Note that Swift also provides two methods called sort() and sort(by:) as counterparts of sorted() and sorted(by:) if you need to sort your collection in-place.

Solution 6 - Arrays

In Swift 3.0

images.sort(by: { (first: imageFile, second: imageFile) -> Bool in
    first. fileID < second. fileID
})

Solution 7 - Arrays

You can also do something like

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

so your images array will be stored as sorted

Solution 8 - Arrays

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.

 struct ImageFile {
      var name: String
      var metadata: String?
      var size: Int
    }
    
    var images: [ImageFile] = [ImageFile(name: "HelloWorld", metadata: nil, size: 256), ImageFile(name: "Traveling Salesmen", metadata: "uh this is huge", size: 1024), ImageFile(name: "Slack", metadata: "what's in this stuff?", size: 2048) ]

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 (<)

    let sizeSmallestSorted = images.sorted { (initial, next) -> Bool in
      return initial.size < next.size
    }

biggest to smallest (>)

    let sizeBiggestSorted = images.sorted { (initial, next) -> Bool in
      return initial.size > next.size
    }

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)

    let nameAscendingSorted = images.sorted { (initial, next) -> Bool in
      return initial.name.compare(next.name) == .orderedAscending
    }

Z-A (.orderedDescending)

    let nameDescendingSorted = images.sorted { (initial, next) -> Bool in
      return initial.name.compare(next.name) == .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.

    let metadataFirst = images.sorted { (initial, next) -> Bool in
      guard initial.metadata != nil else { return true }
      guard next.metadata != nil else { return true }
      return initial.metadata!.compare(next.metadata!) == .orderedAscending
    }

It is possible to have a secondary sort for optionals. For example; one could show images with metadata and ordered by size.

Solution 9 - Arrays

Two alternatives

  1. Ordering the original array with sortInPlace

    self.assignments.sortInPlace({ $0.order < $1.order }) self.printAssignments(assignments)

  2. Using an alternative array to store the ordered array

    var assignmentsO = [Assignment] () assignmentsO = self.assignments.sort({ $0.order < $1.order }) self.printAssignments(assignmentsO)

Solution 10 - Arrays

Swift 4.0, 4.1 & 4.2 First, I created mutable array of type imageFile() as shown below

var arr = [imageFile]()

Create mutable object image of type imageFile() and assign value to properties as shown below

   var image = imageFile()
   image.fileId = 14
   image.fileName = "A"

Now, append this object to array arr

    arr.append(image)

Now, assign the different properties to same mutable object i.e image

   image = imageFile()
   image.fileId = 13
   image.fileName = "B"

Now, again append image object to array arr

    arr.append(image)

Now, we will apply Ascending order on fileId property in array arr objects. Use < symbol for Ascending order

 arr = arr.sorted(by: {$0.fileId < $1.fileId}) // arr has all objects in Ascending order
 print("sorted array is",arr[0].fileId)// sorted array is 13
 print("sorted array is",arr[1].fileId)//sorted array is 14

Now, we will apply Descending order on on fileId property in array arr objects. Use > symbol for Descending order

 arr = arr.sorted(by: {$0.fileId > $1.fileId}) // arr has all objects in Descending order
 print("Unsorted array is",arr[0].fileId)// Unsorted array is 14
 print("Unsorted array is",arr[1].fileId)// Unsorted array is 13

In Swift 4.1. & 4.2 For sorted order use

let sortedArr = arr.sorted { (id1, id2) -> Bool in
  return id1.fileId < id2.fileId // Use > for Descending order
}

Solution 11 - Arrays

You return a sorted array from the fileID property by following way:

Swift 2

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

Swift 3 OR 4

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

Swift 5.0

let sortedArray = images.sorted {
    $0.fileID < $1.fileID
}

Solution 12 - Arrays

If you are going to be sorting this array in more than one place, it may make sense to make your array type Comparable.

class MyImageType: Comparable, Printable {
    var fileID: Int

    // For Printable
    var description: String {
        get {
            return "ID: \(fileID)"
        }
    }
    
    init(fileID: Int) {
        self.fileID = fileID
    }
}

// For Comparable
func <(left: MyImageType, right: MyImageType) -> Bool {
    return left.fileID < right.fileID
}

// For Comparable
func ==(left: MyImageType, right: MyImageType) -> Bool {
    return left.fileID == right.fileID
}

let one = MyImageType(fileID: 1)
let two = MyImageType(fileID: 2)
let twoA = MyImageType(fileID: 2)
let three = MyImageType(fileID: 3)

let a1 = [one, three, two]

// return a sorted array
println(sorted(a1)) // "[ID: 1, ID: 2, ID: 3]"

var a2 = [two, one, twoA, three]

// sort the array 'in place'
sort(&a2)
println(a2) // "[ID: 1, ID: 2, ID: 2, ID: 3]"

Solution 13 - Arrays

If you are not using custom objects, but value types instead that implements Comparable protocol (Int, String etc..) you can simply do this:

myArray.sort(>) //sort descending order

An example:

struct MyStruct: Comparable {
    var name = "Untitled"
}

func <(lhs: MyStruct, rhs: MyStruct) -> Bool {
    return lhs.name < rhs.name
}
// Implementation of == required by Equatable
func ==(lhs: MyStruct, rhs: MyStruct) -> Bool {
    return lhs.name == rhs.name
}

let value1 = MyStruct()
var value2 = MyStruct()

value2.name = "A New Name"

var anArray:[MyStruct] = []
anArray.append(value1)
anArray.append(value2)

anArray.sort(>) // This will sort the array in descending order

Solution 14 - Arrays

I do it like this and it works:

var images = [imageFile]() images.sorted(by: {$0.fileID.compare($1.fileID) == .orderedAscending })

Solution 15 - Arrays

If you want to sort original array of custom objects. Here is another way to do so in Swift 2.1

var myCustomerArray = [Customer]()
myCustomerArray.sortInPlace {(customer1:Customer, customer2:Customer) -> Bool in
    customer1.id < customer2.id
}

Where id is an Integer. You can use the same < operator for String properties as well.

You can learn more about its use by looking at an example here: Swift2: Nearby Customers

Solution 16 - Arrays

var students = ["Kofi", "Abena", "Peter", "Kweku", "Akosua"]

students.sort(by: >)

print(students)

Prints : "["Peter", "Kweku", "Kofi", "Akosua", "Abena"]"

Solution 17 - Arrays

If the array elements conform to Comparable, then you can simply use functional syntax:

array.sort(by: <)

If you're sorting based on a custom type, all you need to do is implement the < operator:

class ImageFile {
	let fileName: String
	let fileID: Int
	let fileSize: Int
	static func < (left: ImageFile, right: ImageFile) -> Bool {
		return left.fileID < right.fileID
	}
}

However, sometimes you don't want one standard way of comparing ImageFiles. Maybe in some contexts you want to sort images based on fileID, and elsewhere you want to sort based on fileSize. For dynamic comparisons, you have two options.

sorted(by:)
images = images.sorted(by: { a, b in
	// Return true if `a` belongs before `b` in the sorted array
	if a.fileID < b.fileID { return true }
	if a.fileID > b.fileID { return false }
	// Break ties by comparing file sizes
	return a.fileSize > b.fileSize
})

You can simplify the syntax using a trailing closure:

images.sorted { ... }

But manually typing if statements can lead to long code (if we wanted to break file size ties by sorting based on file names, we would have quite an if chain of doom). We can avoid this syntax by using the brand-new SortComparator protocol (macOS 12+, iOS 15+):

sorted(using:)
files = files.sorted(using: [
	KeyPathComparator<ImageFile>(\.fileID, order: .forward),
	KeyPathComparator<ImageFile>(\.fileSize, order: .reverse),
])

This code sorts the files based on their file ID (.forward means ascending) and breaks ties by sorting based on file size (.reverse means descending). The \.fileID syntax is how we specify key paths. You can expand the list of comparators as much as you need.


(PS: For some reason, Apple has named the associated type of SortComparator as Compared. It really ought to be called Comparand.)

Solution 18 - Arrays

Swift 3 & 4 & 5

I had some problem related to lowercase and capital case

so I did this code

let sortedImages = images.sorted(by: { $0.fileID.lowercased() < $1.fileID.lowercased() })

and then use sortedImages after that

Solution 19 - Arrays

Sort using KeyPath

you can sort by KeyPath like this:

myArray.sorted(by: \.fileName, <) /* using `<` for ascending sorting */

By implementing this little helpful extension.

extension Collection{
    func sorted<Value: Comparable>(
        by keyPath: KeyPath<Element, Value>,
        _ comparator: (_ lhs: Value, _ rhs: Value) -> Bool) -> [Element] {
        sorted { comparator($0[keyPath: keyPath], $1[keyPath: keyPath]) }
    }
}

Hope Swift add this in the near future in the core of the language.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionmodusView Question on Stackoverflow
Solution 1 - ArraysAlex WayneView Answer on Stackoverflow
Solution 2 - ArraysGoZonerView Answer on Stackoverflow
Solution 3 - ArraysquemefulView Answer on Stackoverflow
Solution 4 - Arraysfujianjin6471View Answer on Stackoverflow
Solution 5 - ArraysImanou PetitView Answer on Stackoverflow
Solution 6 - Arraysjaiswal RajanView Answer on Stackoverflow
Solution 7 - ArraysNicolas GreniéView Answer on Stackoverflow
Solution 8 - ArraysjnblanchardView Answer on Stackoverflow
Solution 9 - ArraysBernauerView Answer on Stackoverflow
Solution 10 - ArraysGurjinder SinghView Answer on Stackoverflow
Solution 11 - ArraysVicky PrajapatiView Answer on Stackoverflow
Solution 12 - ArrayskwerleView Answer on Stackoverflow
Solution 13 - ArraysdorianView Answer on Stackoverflow
Solution 14 - ArraysIllya KritView Answer on Stackoverflow
Solution 15 - ArraysHannyView Answer on Stackoverflow
Solution 16 - ArraysSiddharth ChauhanView Answer on Stackoverflow
Solution 17 - ArraysMcKinleyView Answer on Stackoverflow
Solution 18 - ArraysAbdelrahman MohamedView Answer on Stackoverflow
Solution 19 - ArraysMojtaba HosseiniView Answer on Stackoverflow