Skip to content

Instantly share code, notes, and snippets.

@Asheshp23
Last active September 16, 2024 21:50
Show Gist options
  • Save Asheshp23/739cc944298f31727cb5d624995a84fe to your computer and use it in GitHub Desktop.
Save Asheshp23/739cc944298f31727cb5d624995a84fe to your computer and use it in GitHub Desktop.
import SwiftUI
// MARK: - Data Models
// Struct for representing a student
struct Student: Identifiable {
let id = UUID()
let name: String
let age: Int
let grades: [Double]
}
// Struct for representing processed student information
struct StudentInfo: Identifiable {
let id = UUID()
let averageGrade: Double
let name: String
}
// MARK: - Sample Data
let students = [
Student(name: "Alice", age: 20, grades: [90.0, 85.0, 70.0]),
Student(name: "Bob", age: 17, grades: [70.0, 60.0, 80.0]), // Will be filtered out
Student(name: "Charlie", age: 22, grades: [95.0]), // Needs penalty grades
Student(name: "Dave", age: 18, grades: [88.0, 92.0, 80.0]),
Student(name: "Eve", age: 19, grades: [77.0, 66.0]) // Needs one penalty grade
]
// Part 1
// MARK: - Data Processing Function
// Implement a function to process an array of Student objects into an array of StudentInfo objects.
// Requirements:
// - Filter out students younger than 18 years old.
// - Ensure each student has exactly three grades (add a penalty grade of 50.0 if fewer than three).
// - Calculate the average grade from exactly three grades.
// - Sort the resulting list by average grade in descending order, and by name in ascending order if grades are equal.
func processStudents(students: [Student]) -> [StudentInfo] {
let studentsFilteredByAge = students.filter({ $0.age < 19 })
let studentInfoArray: [StudentInfo] = studentsFilteredByAge.map { student in
var grades = student.grades
while grades.count < 3 {
grades.append(50.0)
}
let averageGrades = grades.reduce(0, +) / 3
return StudentInfo(averageGrade: averageGrades, name: student.name)
}
let sortedStudents = studentInfoArray
.sorted(by: {
if $0.averageGrade == $1.averageGrade {
$0.name < $1.name
} else {
$0.averageGrade > $1.averageGrade
}
})
return sortedStudents
}
// Part 2 (Time allowing)
// MARK: - SwiftUI View
// ContentView: Implement a SwiftUI view named ContentView.
// Requirements:
// - Display a list of StudentInfo objects.
// - Show each student's name and their average grade formatted to two decimal places.
struct ContentView: View {
@State var studentInfoList: [StudentInfo] = []
var body: some View {
VStack {
List {
ForEach(studentInfoList) { studentInfo in
HStack {
Text(studentInfo.name)
Text("\(studentInfo.averageGrade)")
}
}
}
}
.onAppear {
loadStudentsData()
}
}
@MainActor
func loadStudentsData() {
studentInfoList = processStudents(students: students)
}
}
// MARK: - SwiftUI Preview
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment