When to call super

As you may notice, exactly when you call super can have an important effect on your overridden method.

Suppose you have an alternate implementation of recordGrade(_:) that recalculates the failedClasses each time a grade is recorded:

override func recordGrade(_ grade: Grade) { var newFailedClasses: [Grade] = []

for grade in grades {

if grade.letter == "F" { newFailedClasses.append(grade)

}

}

failedClasses = newFailedClasses

super.recordGrade(grade)

}

This version of recordGrade(_:) uses the grades array to find the current list of failed classes. If you’ve spotted a bug in the code above, good job! Because you call super last, if the new grade.letter is an F, the code won’t update the failedClasses array properly.

While it’s not a hard rule, it’s generally best practice to call the super version of a method first when overriding. That way, the superclass won’t experience any side effects introduced by its subclass, and the subclass won’t need to know the superclass’s implementation details.

results matching ""

    No results matching ""