Why convenience keyword is even needed in Swift?

后端 未结 6 931
后悔当初
后悔当初 2020-12-02 04:06

Since Swift supports method and initializer overloading, you can put multiple init alongside each other and use whichever you deem convenient:

c         


        
6条回答
  •  渐次进展
    2020-12-02 04:47

    According to the Swift 2.1 documentation, convenience initializers have to adhere to some specific rules:

    1. A convenience initializer can only call intializers in the same class, not in super classes (only across, not up)

    2. A convenience initializer has to call a designated initializer somewhere in the chain

    3. A convenience initializer cannot change ANY property before it has called another initializer - whereas a designated initializer has to initialize properties that are introduced by the current class before calling another initializer.

    By using the convenience keyword, the Swift compiler knows that it has to check for these conditions - otherwise it couldn't.

提交回复
热议问题