What is the difference between private method and private extension

Hi,


I'm wondering if there is a difference having a private method or the method within a private extension? Does one of both solution have a better influence for the compile time or final object size? Right now do we use a private extension to hide all internal methods grouped within on part of the file.


I was looking into the ARKit2 Sample project with the SlingShot game. There is for example private method being used within the class. Have Apple somewhere a guidance which pattern should we use?


Best,

Thomas

Replies

Are you talking about 'private' and 'file private'...?


With Swift 4.0, scope of

private
and
fileprivate
is extended.
Private is now accessible within same file, outside actual class/extension. If you declare/define your extension in other file, then your private variable will not be accessible at that time fileprivate will work

File Private
File-private access restricts the use of an entity to its own defining source file. Use file-private access to hide the implementation details of a specific piece of functionality when those details are used within an entire file.
Syntax:

fileprivate <var type> <variable name>

Example:
fileprivate class SomeFilePrivateClass {}

Private
Private access restricts the use of an entity to the enclosing declaration, and to extensions of that declaration that are in the same file. Use private access to hide the implementation details of a specific piece of functionality when those details are used only within a single declaration.
Syntax:

private <var type> <variable name>

Example:
private class SomePrivateClass {}

Here is more detail about all access levels: Swift - Access Levels

There's no difference between marking an extension private, or marking individual declarations within an extension private. It's a matter of personal preference. (However, you can't declare an extension private if it's adding a protocol conformance.)


The details are here:


https://docs.swift.org/swift-book/LanguageGuide/AccessControl.html


The section on extensions is near the end.


Finally: member "privacy" is applied across all extensions in the same source file. A private member declared in one extension is usable by all members of the type declared in the file, not just those declared in the same extension. This wasn't true until Swift 4. Before that, you had to use (the old equivalent of) "fileprivate" to get this behavior.