Swift如何对两个自定义对象数组应用切换排序(升序,降序)

时间:2014-09-21 16:57:12

标签: arrays sorting swift

我有一个名为student的类,它包含三个属性。

class Student  {
     var name = String()
     var age = Int()
     var school = String()
}


var studentrecord : Array = []

var student = Student()
student.name = "John"
student.age = 15
student.school = "abc"



var student1 = Student()
student1.name = "Tom"
student1.age = 14
student1.school = "pqr"


var student2 = Student()
student2.name = "Alex"
student2.age = 16
student2.school = "xyz"


studentrecord.append(student)
studentrecord.append(student1)
studentrecord.append(student2)

如何通过" name"对学生记录array进行排序?上下两个(Toggle Sort)?

3 个答案:

答案 0 :(得分:2)

您可以通过传入不同的排序函数来控制排序顺序:

func acs(s1:Student, s2:Student) -> Bool {
    return s1.name < s2.name
}
func des(s1:Student, s2:Student) -> Bool {
    return s1.name > s2.name
}
var n1 = sorted(studentrecord, acs) // Alex, John, Tom
var n2 = sorted(studentrecord, des) // Tom, John, Alex

您必须编写GUI代码,以便在用户切换按钮时决定使用哪种排序功能。

答案 1 :(得分:0)

这是一个与排序方法一样的版本,

extension Array{

  func toggleSort(predicate: (T, T) -> Bool, reverse: Bool ) -> [T]{
   var a = self

    a.sort({
      (obj1, obj2) in

      if reverse{

        return !predicate(obj1, obj2)
      }
      return predicate(obj1, obj2)
    })

    return a
  }


}


var sorted  = studentrecord.toggleSort({ $0.name < $1.name}, reverse: false)


var reverseSorted = studentrecord.toggleSort({ $0.name < $1.name}, reverse: true)

答案 2 :(得分:0)

我认为最简单的方法是:

items.sort(ascending ? {$0.name < $1.name} : {$0.name > $1.name})