按两个属性对对象数组进行排序

时间:2015-04-09 05:41:34

标签: swift sorting

在使用NSSortDescriptor之前,已经提出并回答了这个问题。但使用Array.sort()

是否采用Swift标准方式
struct Sortable {
    let isPriority: Bool
    let ordering: Int
}

通过一个属性对Sortables数组进行排序很简单:

sort { $0.ordering < $1.ordering }

但我希望按isPriority排序,然后按ordering排序 - 我无法理解这个简单的陈述。

4 个答案:

答案 0 :(得分:42)

是的,有一种使用Array.sort()

的简单方法

<强>代码:

var sorted = array.sorted({ (s1, s2) -> Bool in
    if s1.isPriority && !s2.isPriority {
        return true //this will return true: s1 is priority, s2 is not
    }
    if !s1.isPriority && s2.isPriority {
        return false //this will return false: s2 is priority, s1 is not
    }
    if s1.isPriority == s2.isPriority {
        return s1.ordering < s2.ordering //if both save the same priority, then return depending on the ordering value
    }
    return false
})

排序数组:

true - 10
true - 10
true - 12
true - 12
true - 19
true - 29
false - 16
false - 17
false - 17
false - 17
false - 18

另一个更短的解决方案:

let sorted = array.sorted { t1, t2 in 
   if t1.isPriority == t2.isPriority {
      return t1.ordering < t2.ordering 
   }
   return t1.isPriority && !t2.isPriority 
}

答案 1 :(得分:13)

以下是进行此排序的简单说明:

var sorted = array.sort { $0.isPriority == $1.isPriority ? $0.ordering < $1.ordering : $0.isPriority && !$1.isPriority }

答案 2 :(得分:1)

我在Swift 3中创建了一篇关于如何使用它的博客文章,并保持代码简单易读。

你可以在这里找到它:

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

您还可以在此处找到包含以下代码的GitHub存储库:

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

这一切的要点,比方说,如果您有位置列表,您将能够这样做:

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
        )

答案 3 :(得分:0)

符合Comparable! ?

extension Sortable: Comparable {
  static func < (sortable0: Sortable, sortable1: Sortable) -> Bool {
    sortable0.isPriority == sortable1.isPriority
    ? sortable0.ordering < sortable1.ordering
    : sortable0.isPriority
  }
}

这将允许:

sortableArray.sorted()