swift3.0 基礎練習-構造對象並按要求進行排序(struct)

struct練手

``````struct Student{
var name:String
var mathScore:Int
var englishScore:Int
var average:Float

//MARK: - 初始化並求平均值
init(name:String,mathScore:Int,englishScore:Int) {
self.name = name
self.mathScore = mathScore
self.englishScore = englishScore
self.average = Float(self.mathScore + self.englishScore) / 2
}
}``````

``````func sortWithAverage(students:[Student]) -> [Student] {
var result = students
for i in 0..<result> result[j].average) {
let tmp = result[i]
result[i] = result[j]
result[j] = tmp
}
}
}
return result
}``````

``````//構造10個學生對象
var student01 = Student(name: "st01", mathScore: 67, englishScore: 98)
var student02 = Student(name: "st02", mathScore: 87, englishScore: 56)
var student03 = Student(name: "st03", mathScore: 47, englishScore: 86)
var student04 = Student(name: "st04", mathScore: 65, englishScore: 88)
var student05 = Student(name: "st05", mathScore: 85, englishScore: 97)
var student06 = Student(name: "st06", mathScore: 85, englishScore: 94)
var student07 = Student(name: "st07", mathScore: 92, englishScore: 76)
var student08 = Student(name: "st08", mathScore: 93, englishScore: 66)
var student09 = Student(name: "st09", mathScore: 63, englishScore: 93)
var student10 = Student(name: "st10", mathScore: 99, englishScore: 82)

//調用排序方法
var result = sortWithAverage(students: [student01,
student02,
student03,
student04,
student05,
student06,
student07,
student08,
student09,
student10])

print("英語和數學平均分的成績從小到大排列為:")
//遍歷結果數組並打印
for i in 0..<result.count{
print("姓名:\(result[i].name),數學成績:\(result[i].mathScore),英語成績:\(result[i].englishScore),平均分:\(result[i].average)")
}``````