Swift - Sort array of objects with multiple criteria

后端 未结 8 1133
北荒
北荒 2020-11-22 11:19

I have an array of Contact objects:

var contacts:[Contact] = [Contact]()

Contact class:

Class Contact:NSOBjec         


        
8条回答
  •  广开言路
    2020-11-22 12:11

    The one thing the lexicographical sorts cannot do as described by @Hamish is to handle different sorting directions, say sort by the first field descending, the next field ascending, etc.

    I created a blog post on how to this in Swift 3 and keep the code simple and readable.

    You can find it here:

    http://master-method.com/index.php/2016/11/23/sort-a-sequence-i-e-arrays-of-objects-by-multiple-properties-in-swift-3/

    You can also find a GitHub repository with the code here:

    https://github.com/jallauca/SortByMultipleFieldsSwift.playground

    The gist of it all, say, if you have list of locations, you will be able to do this:

    struct Location {
        var city: String
        var county: String
        var state: String
    }
    
    var locations: [Location] {
        return [
            Location(city: "Dania Beach", county: "Broward", state: "Florida"),
            Location(city: "Fort Lauderdale", county: "Broward", state: "Florida"),
            Location(city: "Hallandale Beach", county: "Broward", state: "Florida"),
            Location(city: "Delray Beach", county: "Palm Beach", state: "Florida"),
            Location(city: "West Palm Beach", county: "Palm Beach", state: "Florida"),
            Location(city: "Savannah", county: "Chatham", state: "Georgia"),
            Location(city: "Richmond Hill", county: "Bryan", state: "Georgia"),
            Location(city: "St. Marys", county: "Camden", state: "Georgia"),
            Location(city: "Kingsland", county: "Camden", state: "Georgia"),
        ]
    }
    
    let sortedLocations =
        locations
            .sorted(by:
                ComparisonResult.flip <<< Location.stateCompare,
                Location.countyCompare,
                Location.cityCompare
            )
    

提交回复
热议问题