Author Topic: Preventing Overriding Question  (Read 8201 times)


  • Newbie
  • *
  • Posts: 8
    • View Profile
Preventing Overriding Question
« on: January 28, 2015, 10:09:27 AM »
Kevin in the Preventing Overriding example you said that you could prevent someone from overriding a member of a class by using the final modifier.  I was playing around and wrote the following code;

Code: [Select]
class PatientSecureEntity2: PatientEntity {
    override final var SSN: String {
        get {
            let index = advance(super.SSN.startIndex, 7)
            var ss = super.SSN.substringFromIndex(index)
            return "***-**-\(ss)"
        set {
            super.SSN = newValue

var ps2 = PatientSecureEntity2()

ps2.SSN = "987-65-4321"

I was surprised to see that the SSN was changed.  The experiment just prior to this topic, commenting out the setter, did work as explained in the book.  Did something in Swift change  since this writing or am I doing something wrong in my code?



  • Global Moderator
  • *****
  • Posts: 25
    • View Profile
Re: Preventing Overriding Question
« Reply #1 on: July 15, 2016, 12:14:03 PM »
Hello Dave, the reason you are able to override the SSN is because you did not subclass PatientSecureEntity2 class and try to override the SSN property in that new subclass.  Once you do that then you will see that the final modifier does work as intended.  Page 252 of the book says, "At times, you may want to prevent someone from overriding a member of a class or an entire class. Do this by using the final modifier. For example, if you don’t want anyone overriding the SSN property of the PatientSecureEntity class, you can mark it with the final modifier…”  The key word her is “overriding.”  If you try to override the final property in a new subclass you will get a compile-time error.  Apple’s documentation on Preventing Overrides says, "You can prevent a method, property, or subscript from being overridden by marking it as final. Do this by writing the final modifier before the method, property, or subscript’s introducer keyword (such as final var, final func, final class func, and final subscript). Any attempt to override a final method, property, or subscript in a subclass is reported as a compile-time error.”  So, try to subclass your PatientSecureEntity2 class and then try to override the SSN property. You should see the compile-time error.  Hope that helps.

Oak Leaf Enterprises, Inc.