Search code examples
arraysswiftcosmicmind

Swift sort array by 2 parameters


The array contains instance of Entity (Graph library for Core Data):

let timCook = Entity(type: "Employees")
timCook["name"] = "Tim Cook"
timCook["company"] = "Apple"

the above code won't work, I think the && is not the right way to sort by multiple values...

self.storage.sortInPlace ({ ($0["company"] as? String) < ($1["company"] as? String)
                             && ($0["name"] as? String) < ($1["name"] as? String)
                         })

thanks


Solution

  • Okay, if you want to sort by company first and then by name, you first have to check for equality of the companies. If the companies are the same, you fall back to sorting by name, otherwise, you just return the result of the comparison between the two companies.

    self.storage.sortInPlace {
        if ($0["company"] as! String) == ($1["company"] as! String)
        {
            return ($0["name"] as! String) < ($1["name"] as! String)
        }
        return $0["company"] as! String) < ($1["company"] as! String)
    }
    

    or even shorter:

    self.storage.sortInPlace { (($0["company"] as! String) == ($1["company"] as! String)) ? (($0["name"] as! String) < ($1["name"] as! String)) : ($0["company"] as! String) < ($1["company"] as! String)) }