Notes: 39. Challenge: Structures
Update Notes: The student materials have been reviewed and are updated as of October 2021.
It’s time for some practice with structures. You can find the challenge in the “06 - Challenge - Structures” page of the playground you’ve been using, or you can download a new one from the resources for this video. Open it up, and try solving the challenge questions on your own, then keep watching to compare your work to mine. Good luck!
The first task is pretty clear. I’ll make a new Student struct:
struct Student {
}
Then add the “First name” and “last name” properties and make them Strings, and I’ll use an Int for the “grade”.
struct Student {
let firstName: String
let lastName: String
let grade: Int
}
Then, onto the Classroom struct:
struct Classroom {
}
This one needs a “subject”–again, a String. And then, a Student array.
struct Classroom {
let subject: String
let students: [Student]
}
For number 3, I’ll start a method called getHighestGrade
func getHighestGrade() {
}
And I’ll have it return an optional Int, because, if students were an empty array, there would be no highest grade.
func getHighestGrade() -> Int? {
There are a few ways you might go about this, but I’m going to collect all of the grades into a new array and then return the highest value from that array. To start, I need an empty grades array:
var grades: [Int] = []
And then I’ll use a for loop to iterate over the students and add their grades to the grades array.
for student in students {
grades.append(student.grade)
}
Finally, with that array as populated with all of the grades, I can use the max method, to pick out the highest one.
return grades.max()
First, I’ll make an instance of a classroom with Catie, me, and Salvador Dalí as students.
53 let classroom = Classroom(
className: "Usable Clock Design",
students: [
Student(firstName: "Chris", lastName: "Belanger", grade: 75),
Student(firstName: "Catie", lastName: "Catterwaul", grade: 95),
Student(firstName: "Salvador", lastName: "Dalí", grade: 2)
]
)
And now I can use the getHighestGrade method to pull out the highest grade.
classroom.getHighestGrade()
With a 75, I didn’t get the highest grade, but my clock designs were still …fairly usable. They didn’t melt, but they only told the right time twice a day.