Swift 2.0 Sorting Array of Objects by Property

前端 未结 4 1764
隐瞒了意图╮
隐瞒了意图╮ 2020-12-14 14:43

In Swift 2.0, how would you go about sorting an array of custom objects by a property? I know in Swift 1.2, this was done using sorted() and sort(). However, these methods n

4条回答
  •  北荒
    北荒 (楼主)
    2020-12-14 15:03

    In Swift 2:

    • You can use sort method, using compare to compare the two dates:

      let sortedArray = myArray.sort { $0.myDate.compare($1.myDate) == .OrderedAscending }  // use `sorted` in Swift 1.2
      
    • Or, if you want to sort the original array, you can sortInPlace:

      myArray.sortInPlace { $0.myDate.compare($1.myDate) == .OrderedAscending }  // use `sort` in Swift 1.2
      

    In Swift 3:

    • to return a sorted rendition of the array, use sorted, not sort

      let sortedArray = myArray.sorted { $0.myDate < $1.myDate }
      
    • to sort in place, it's now just sort:

      myArray.sort { $0.myDate < $1.myDate }
      

    And with Swift 3's Date type, you can use the < operator.

提交回复
热议问题