Home > Back-end >  Is there a difference when you create a private func vs creating a func in a private extension?
Is there a difference when you create a private func vs creating a func in a private extension?

Time:12-17

Can I create private functions by putting my functions inside of a private extension of the class instead of creating new private functions by constantly calling private func functionName(){}?

Doing this:

private extension mClass {
    func mFuncOne(){}
    func mFuncTwo(){}
    func mFuncThree(){}
    func mFuncFour(){}
    func mFuncFive(){}
}

instead of:

class mClass {
    private func mFuncOne(){}
    private func mFuncTwo(){}
    private func mFuncThree(){}
    private func mFuncFour(){}
    private func mFuncFive(){}
}

CodePudding user response:

Technically, the difference is that the private extension makes the methods fileprivate, not private.

But the real question is why would one use a private extension rather than just declaring the individual methods as private?

We do this because:

  • extensions facilitate the organization of our code, separating methods into logical groupings (e.g., it avoids intermingling private implementation details with public interface);
  • the use of extensions affords code collapse of entire groups of methods within the Xcode IDE; and
  • the marking of the whole extension as private avoids the syntactic noise of repeating private keyword for each method.

So, private methods and methods inside a private extension are not technically the same thing, but the difference is subtle and the private extension pattern is, nonetheless, extremely convenient. It concisely designates that none of the methods contained within are used outside of the current file.

CodePudding user response:

Yes you can do this. It's just that the extension and the original declaration has to be in the same file. According to the Swift Guide:

Extensions that are in the same file as the class, structure, or enumeration that they extend behave as if the code in the extension had been written as part of the original type’s declaration. As a result, you can:

  • ...
  • Declare a private member in an extension, and access that member from the original declaration in the same file.
  • Related