How to Sort an Array in Swift

How to sort an array of custom objects by property value in Swift

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.

How do I sort an array of an array in Swift 5

You can do in following way:

a.sort {
return $0.last as! Int > $1.last as! Int

Don't forget to add additional checks while using this code, case where the last item is not an integer or there is an array not in the expected format. Otherwise, it will lead to a crash.

Sort an array A in Swift based on (1) an incomplete array B and (2) alphabetically

Based on this answer mentioned by Alexander I ended up with the following solution:

tags.sort {
(idOrdering.firstIndex(of: $ ?? idOrdering.count, $ <
(idOrdering.firstIndex(of: $ ?? idOrdering.count, $

Sort array based on the order from another array Swift

You can try the following in Swift. Note the dictionaries in Swift are unordered so you have to use arrays for ordered collections:

let fetchedProducts = [
(name: "productName20", id: 20),
(name: "productName3", id: 3),
(name: "productName1", id: 1),
let sortedProducts = [
("productName1", "1"),
("productName20", "20"),
("productName3", "3"),
let sortedFetchedProducts = sortedProducts
.compactMap { s in
fetchedProducts.first(where: { s.1 == String($ })

// [(name: "productName1", id: 1), (name: "productName20", id: 20), (name: "productName3", id: 3)]

Swift sorting nest String Array by Numbered Array Sort

You can get an index from one array and sort using values from the second array:

let a = [["ddd"],["aaa"],["ggg"]]
let b = [557, 147, 355]

let sortedA = a.sorted { b[a.firstIndex(of: $0)!] < b[a.firstIndex(of: $1)!] }
// prints [["aaa"], ["ggg"], ["ddd"]]

let sortedB = b.sorted()
// prints [147, 355, 557]

This one-liner:

let sortedA = a.sorted { b[a.firstIndex(of: $0)!] < b[a.firstIndex(of: $1)!] }

is a shorter form of this:

let sortedA = a.sorted { item1, item2 in
let item1Index = a.firstIndex(of: item1)!
let item2Index = a.firstIndex(of: item2)!
return b[item1Index] < b[item2Index]

Swift sorted(by:) method doesn't correctly sort an array of struct based on integer

The predicate to Array.sorted(by:) requires that you

return true if its first argument should be ordered before its second argument; otherwise, false.

The order of the arguments passed to the predicate can be given in either order ((a, b) or (b, a)) depending on how the list has been sorted so far, but the predicate must give a consistent result in either order or else you'll get nonsense results.

In your predicate, you're checking the first element's user ID to prioritize it, but not the second; i.e., you're handling (a, b) but not (b, a). If you update your predicate to

myArray.sorted(by: {
// The order of the checking here matters. Specifically, the predicate
// requires a `<` relationship, not a `<=` relationship. If both $0 and $1
// have the same `user_id`, we need to return `false`. Checking $1.user_id
// first hits two birds with one stone.
if $1.user_id == 40 {
return false
} else if $0.user_id == 40 {
return true

return $0.user_id < $1.user_id

then you'll get consistent results.

Alternatively, if the element is known ahead of time, you can avoid this by extracting it from the list and sorting the remaining results.

Sort array ascending with zero at the end in Swift

Replace any 0 encountered with a large number like Int.max in the areInIncreasingOrder predicate parameter for sorted:

let score = [3, 0, 4, 6]
let ranking = score.sorted{ ($0 == 0 ? Int.max : $0) < ($1 == 0 ? Int.max : $1) }


[3, 4, 6, 0]

Related Topics

Leave a reply