Marcello Catelli Marcello Catelli - 6 months ago 22
Swift Question

Swift sort array by 2 parameters

The array contains instance of Entity (Graph library for Core Data), no crash but 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

Answer

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)) }
Comments