Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between fileprivate and private extension?

Swift 3.0

I know that fileprivate access level modifier limited using of function/property to source file where it was declared and private - limited to lexical scope where was declared. But it seems that this rule not apply for extensions. E.G. this code is valid:

class Foo {
}

fileprivate extension Foo {
    var aa: Int {
        return aaa + 10
    }
}

private extension Foo {
    var aaa: Int {
        return 20
    }
}

Can someone help me figured out difference between them? Thanks.

Swift 4.0

private is now accessible in extension but within same file. If you declare/define extension in other file, then your private variable will not be accessible to your extension.

fileprivate is accessible within same file.

like image 845
Bohdan Savych Avatar asked Apr 07 '17 21:04

Bohdan Savych


People also ask

What is a private extension?

Private extensions are extensions that you have explicitly allowed for use in your AWS account.

Can we use Fileprivate in extension?

fileprivate allows use only within the defining source file. private allows use only from the enclosing declaration and since Swift 4, to any extensions of that declaration in the same source file.

When should I use Fileprivate?

Fileprivate access restricts the use of an entity within the same defined source file. The only reason you would use fileprivate is when you want to access your code within the same file from different classes or structs.

Can we access Fileprivate variable in extension Swift?

Swift 3 added the fileprivate keyword. An entity that is declared fileprivate is only accessible from within the file it is defined in.


1 Answers

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

like image 113
Krunal Avatar answered Sep 30 '22 17:09

Krunal