derdida
derdida

Reputation: 14904

Swift order objects by property

I have an array of objects and i would like to order it. Thats normally not a huge problem, but in my special case i would like to order string values like:

CAT-1, CAT-2, ....CAT-10

Where now CAT-10 is before CAT-2.

I already found that i can sort string values in this case with:

let items = items.sorted {
    (s1, s2) -> Bool in return s1.localizedStandardCompare(s2) == .orderedAscending
}

But this is only working when the the array contains only string values. In my case i would like to sort it with something like this:

self.filteredItems.sort{ 
    return $0.position < $1.position
}

But i am not sure how can i combine the function above to solve that special sort order?

Upvotes: 0

Views: 38

Answers (1)

Vini App
Vini App

Reputation: 7485

Please check:

class Category {
    let name: String

    init(_ name: String) {
        self.name = name
    }
}

var catA = Category("CAT-2")
var catB = Category("CAT-10")
var catC = Category("CAT-1")

let items: [Category] = [catA, catB, catC]
let filteredItems: [Category] = items.sorted { (s1, s2) -> Bool in
    return s1.name.localizedStandardCompare(s2.name) == .orderedAscending
}
print(filteredItems[0].name, filteredItems[1].name, filteredItems[2].name)
// Output : CAT-1 CAT-2 CAT-10

let sortedBy = items.sorted { (c1, c2) -> Bool in
    return c1.name < c2.name
}
print(sortedBy[0].name, sortedBy[1].name, sortedBy[2].name)
// Output : CAT-1 CAT-10 CAT-2

Upvotes: 1

Related Questions