Swift - 如何对自定义类数组进行排序?

时间:2015-09-10 23:18:48

标签: ios arrays iphone swift sorting

这是我的代码。如您所见,我正在使用自定义类。我创建了一系列学生,我想对它进行排序。我知道我必须使用sort函数,但我不知道如何使用它。我明白我需要创建一个需要两个学生的函数并返回一个布尔值。

即使我知道代码不是100%正确,我知道我想专注于调用sort函数。

class Subject{

    var id:Int

    var name: String

    init(id:Int, name:String){

        self.id = id

        self.name = name

    }

}



class Helper{

    static func isFirstStudentBetterThanTheSecondStudent(student1: Student, student2: Student) -> Bool{

        if student1.subjects == nil{

            return false

        }

        var student1Marks: Double = 0

        for index in student1.marks!{

            student1Marks += index

        }



        var student2Marks :Double = 0

        for index in student2.marks!{

            student2Marks += index

        }



        return student1Marks > student2Marks

    }

}



let subject1 = Subject(id: 1, name: "subject 1")

let subject2 = Subject(id: 2, name: "subject 2")

let subject3 = Subject(id: 3, name: "subject 3")



let student1 = Student(number: 1, fullName: "student 1")

student1.addSubject(subject1, result: 10)

student1.addSubject(subject2, result: 20)

student1.addSubject(subject3, result: 30)



let student2 = Student(number: 2, fullName: "student 2")

student2.addSubject(subject1, result: 100)

student2.addSubject(subject2, result: 200)

student2.addSubject(subject3, result: 300)



let students = [student1, student2]

我需要根据我的辅助静态函数对学生数组进行排序。

1 个答案:

答案 0 :(得分:0)

sort函数采用闭包,因为它是参数

let sortedStudent = students.sort({ Helper.isFirstStudentBetterThanTheSecondStudent ($0, student2: $1 ) } )

与完整语法相同的结果:

let sortedSudents2 = students.sort({(s1: Student, s2:Student) -> Bool in return Helper.isFirstStudentBetterThanTheSecondStudent(student1, student2: student2)})

More details