gpt4 book ai didi

swift - 我的 for 循环出了什么问题 - 它没有达到最高等级

转载 作者:行者123 更新时间:2023-11-30 10:46:12 26 4
gpt4 key购买 nike

我有一个 for 循环(在函数内部),应该输出类(class)中的最高成绩。但它并没有在类取得“A”。为什么不呢?

我还预计我的数组索引会生成超出范围的错误,但我没有收到错误。我猜是幸运的,尽管我不确定为什么。

struct Student {
let firstName: String
let lastName: String
let grade: String
}

struct Classroom {
let nameOfClass: String
let students: [Student]

func highGrade(students: [Student]) {
var x: Int = 0

for student in students {
if students[x].grade < students[x + 1].grade {
print(student.grade)
x += 1
}
else {
print("Nope")
}
}
} }

let student1 = Student(firstName: "Keith", lastName: "Grimes", grade: "F")
let student2 = Student(firstName: "Debbie", lastName: "Grimes", grade: "A")
let student3 = Student(firstName: "Nicholas", lastName: "Grimes", grade: "C")

let class1 = Classroom(nameOfClass: "Swift", students: [student1, student2, student3])

class1.highGrade(students: [student1, student2, student3])

我正在尝试找出类三名学生中的最高成绩。

最佳答案

我更喜欢显式初始化程序在初始化时对学生进行排序,如下所示,

struct Classroom {
let nameOfClass: String
let students: [Student]

init(_ className: String, students: [Student]) {
self.nameOfClass = className
self.students = students.sorted(by: { $0.grade < $1.grade })
}
}

用法:

let student1 = Student(firstName: "Keith", lastName: "Grimes", grade: "F")
let student2 = Student(firstName: "Debbie", lastName: "Grimes", grade: "A")
let student3 = Student(firstName: "Nicholas", lastName: "Grimes", grade: "C")

let class1 = Classroom("Swift", students: [student1, student2, student3])
print(class1.students.first?.grade)
print(class1.students.first?.firstName)

输出:

Optional("A")
Optional("Debbie")

关于swift - 我的 for 循环出了什么问题 - 它没有达到最高等级,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55726361/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com