Leave a rating/review
Notes: 41. Challenge: Classes
Update Notes: The student materials have been reviewed and are updated as of October 2021.
It’s time for some practice with classes. You can find the challenge in the “08 - Challenge - Classes” 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!
This code should look familiar! It’s the Student structure from the Structures episode. The challenge is to transform this Struct into a Class. First, I’ll replace the struct keyword with class.
class Student {
}
Now I’m seeing three errors, but two of them can be solved by writing an initializer. First use the keyword init followed by a parameter list with a parameter for each property:
init(name: String, grade: Int, pet: String?) {
<#statements#>
}
You could also set default values for these parameters, just like you would with a function. I’ll make pet default to nil:
init(name: String, grade: Int, pet: String?😺 = nil🛑) {...
To finish up the initializer, I’ll set the property values using the matching parameters:
self.name = name
self.grade = grade
self.pet = pet
Now if I want to make a new Student without a pet, I can use this initializer that only needs two arguments:
let sam = Student(name: "Sam", grade: 99)
Next, I just need to get rid of mutating. As the error says, it doesn’t work with Classes.
❌mutating❌ func earnExtraCredit
All of the errors are gone now, but there’s one more thing I can do. Because this is a class, I can make chris a constant…
😺let🛑 chris = Student(name: "Chris"....
and this earnExtraCredit method will still successfully change this guy’s grade.