Methods and mutability
You’ve seen how a class’s mutability is one its most important attributes. Up to this point, you’ve been mutating classes similarly to how you’ve modified structs, meaning you’ve manipulated a class instance’s stored properties from outside of the object.
Because classes are mutable, it’s also possible for instances to mutate themselves.
struct Grade {
let letter: String let points: Double let credits: Double
}
class Student {
var firstName: String var lastName: String var grades: [Grade] = []
init(firstName: String, lastName: String) { self.firstName = firstName
self.lastName = lastName
}
func recordGrade(_ grade: Grade) { grades.append(grade)
}
}
Somewhat like the Person class, the Student class has a firstName and a lastName property. It also has an array of Grade values that represent that student’s recorded grades.
Note that recordGrade(_:) can mutate the array grades by adding more values to the end. That means you can use that method rather than accessing the grades
array yourself:
let jane = Student(firstName: "Jane", lastName: "Appleseed") let history = Grade(letter: "B", points: 9.0, credits: 3.0) var math = Grade(letter: "A", points: 16.0, credits: 4.0)
jane.recordGrade(history) jane.recordGrade(math)
When you call recordGrade(:) and pass in a grade, it’s the _class itself that modifies its own stored property.
If you had tried this with a struct, you’d have wound up with a build failure, because structures are usually immutable. Remember, when you change the value of a struct, instead of modifying the value, you’re making a new value.