0

I have a class named student and it contains three properties.

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)

How can I sort student record array by "name" ascending and descending both (Toggle Sort)?

viju
  • 91
  • 2
  • 3
  • 14
  • Have a look here: http://stackoverflow.com/questions/24130026/swift-how-to-sort-array-of-custom-objects-by-property-value – sbarow Sep 21 '14 at 17:16
  • 1
    i have looked that link, ascending or descending mentioned. i need toggle sort i.e ascending and descending both on button click. – viju Sep 21 '14 at 17:22

3 Answers3

2

You can control the sorting order by passing in a different sorting function:

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

You must write your GUI code such that it can decide which sorting function to use when a user toggles the button.

Anthony Kong
  • 37,791
  • 46
  • 172
  • 304
  • Suppose, i have a sort button, when i press this button, the name should be print ascending order (Alex, John, Tom) and again press, should be name print descending order (Tom, John, Alex) and vice-versa. – viju Sep 21 '14 at 17:32
  • 2
    There is no magic way to wire them up. You have to learn the iOS programming – Anthony Kong Sep 21 '14 at 17:42
1

The simplest way in my opinion is:

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

Here is a version which works just like sort method,

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)
Sandeep
  • 20,908
  • 7
  • 66
  • 106