Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a difference when you create a private func vs creating a func in a private extension?

Tags:

swift

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(){}
}
like image 699
pgs1 Avatar asked Sep 07 '25 02:09

pgs1


1 Answers

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.

like image 166
Rob Avatar answered Sep 09 '25 19:09

Rob