Search code examples
iosswiftpublic

Why need to set public before override viewDidLoad in a public access control viewController


Why need to set public before override viewDidload in a public access control viewController

public class customViewController: UIViewController {
    override public func viewDidLoad() {
        super.viewDidLoad()
    }
}

if I remove the public, Xcode will give an error warning!


Solution

  • The error message is fairly explicit:

    Overriding instance method must be as accessible as the declaration it overrides.

    This means that a method must not have a lower access level than the method it overrides.

    For example given this class:

    public class Superclass {
        internal func doSomething() {
            ...
        }
    }
    

    You cannot then override doSomething with a method that is less accessible than interal. e.g.

    public class Subclass : Superclass {
        // error
        private override func doSomething() {
        }
    }
    

    You can however override a method and make it more accessible:

    public class Subclass : Superclass {
        public override func doSomething() {
            // You can even call the internal method in the superclass
            super.doSomething()
        }
    }
    

    The reference documentation has lots of detail on this, but seems to leave this relationship to implication.