0

Here is a sorting problem that I faced during working on Swift 3. I have an Array with many objects called Feed as follows. The sorting method should include 2 steps: - The objects having the same barcode will stand side-by-side in the array - The object having the same barcode having the status A will stand on the left, the next is the one having status B, then the one with status C.

How to write a sort function to cover those two steps ??

class Feed: Object {

    dynamic var barcode: Int
    dynamic var feed_type = ""

    dynamic var status: String 

    override class func primaryKey() -> String {
        return "id"
    }

    var type: FeedType {
        get {
            return FeedType.get(feed_type)
        }

        set(newValue) {
            feed_type = newValue.key
        }
    }

}
1
  • @Sulthan: Ops my bad. I edited the code Commented Mar 17, 2017 at 10:28

2 Answers 2

1

You can simply chain up the comparison:

let values: [Feed] = ...

let sortedValues: [Feed] = values.sorted { (feed1, feed2) in
    feed1.barcode < feed2.barcode
    || (feed1.barcode == feed2.barcode && feed1.status < feed2.status)
}

Since you are using Objective-C objects, you could also use the old NSSortDescriptor. However, it was not bridged to Swift therefore you need some casting magic:

let barcodeSortDescriptor = NSSortDescriptor(key: "barcode", ascending: true)
let statusSortDescriptor = NSSortDescriptor(key: "status", ascending: true)

let sortedValues: [Feed] = (values as NSArray)
    .sortedArray(using: [barcodeSortDescriptor, statusSortDescriptor]) as! [Feed]

This is especially useful when your sorting is more complicated.

Sign up to request clarification or add additional context in comments.

Comments

1

So in your comparator method you should receive 2 objects. Now do the following stuff.

if(object1.barcode > object2.barcode)
    return false;
else if(object1.barcode < object2.barcode)
    return true;
else {
    if(object1.status > object2.status)
        return false;
    else
        return true;
}

1 Comment

hi @Apurv, I'm a newbie working on Sorting in Swift 3. Could you please give an example of receiving 2 objects in the comparator method? Thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.