Possible to accidentally override a private method?

Is it possible for a subclass to unknowingly override a private method of a superclass, whether Swift or Objective-C?

1 Like

Only if the subclass method is implemented in a scope where the superclass’s method is visible, in which case the override keyword is required.

Example 1: Shadowing, not overriding:

class Super {
  private func foo() { print("Super.foo") }
  func test() { self. foo() }
}

class Sub: Super {
  func foo() { print("Sub.foo") }
}

Sub().test()
// prints "Super.foo"

Example 2: Overriding, keyword requiring:

class Super {
  private func foo() { print("Super.foo") }
  func test() { foo() }
  
  class Sub: Super {
    override func foo() { print("Sub.foo") }
  }
}

Super.Sub().test()
// prints "Sub.foo"
2 Likes

Also, if superclass is written in obj-c override keyword isn't required, which means you can do it unknowingly

1 Like

Right. In Swift you can't accidentally override something without the override keyword, only shadow it at compile time. But in Objective-C, all methods live in one namespace keyed by selector, so if you make a method in a subclass (or extension!) with the same selector you'll replace the original. This is the same situation that's always been true in Objective-C and is another reason not to make your methods @objc unless they need to be!