编辑代码

// 定义学生结构体 Students
struct Students {
    var name: String
    var studentID: String
    var gender: String
    var chineseScore: Double
    var mathScore: Double
    var englishScore: Double

    // 初始化器
    init(name: String, studentID: String, gender: String, chineseScore: Double, mathScore: Double, englishScore: Double) {
        self.name = name
        self.studentID = studentID
        self.gender = gender
        self.chineseScore = chineseScore
        self.mathScore = mathScore
        self.englishScore = englishScore
    }

    // 计算总成绩
    func totalScore() -> Double {
        return chineseScore + mathScore + englishScore
    }
}

// 创建多个学生实例
let s1 = Students(name: "Alice", studentID: "1001", gender: "Female", chineseScore: 85, mathScore: 90, englishScore: 88)
let s2 = Students(name: "Bob", studentID: "1002", gender: "Male", chineseScore: 78, mathScore: 85, englishScore: 92)
let s3 = Students(name: "Carol", studentID: "1003", gender: "Female", chineseScore: 92, mathScore: 88, englishScore: 86)

// 学生数组
let students = [s1, s2, s3]

// 输出信息提示用户输入
print("请输入要查找的学生姓名或学号:")
if let input = readLine() {
    var foundStudent: Students?

    // 遍历学生数组,查找学生
    for student in students {
        if student.name == input || student.studentID == input {
            foundStudent = student
            break
        }
    }

    // 输出查找结果
    if let student = foundStudent {
        print("查找到学生:")
        print("姓名:\(student.name)")
        print("学号:\(student.studentID)")
        print("性别:\(student.gender)")
        print("语文成绩:\(student.chineseScore)")
        print("数学成绩:\(student.mathScore)")
        print("英语成绩:\(student.englishScore)")
    } else {
        print("未找到学生")
    }
}