Nikita P Nikita P - 3 months ago 55
Swift Question

What is a good example to differentiate between fileprivate and private in swift3

https://lists.swift.org/pipermail/swift-evolution/Week-of-Mon-20160328/013664.html has been helpful in understanding what the new access-specifiers are in Swift3. It also gives some examples of different usage of

fileprivate
and
private
.

My question is, Isn't using
fileprivate
on a function that is going to be used only in this file, same as using
private
?

Answer

fileprivate is now what what private used to be in earlier Swift releases: accessible from the same source file. A declaration marked as private can now only be accessed within the lexical scope it is declared in. So private is more restrictive than fileprivate.

Example (all in one source file):

class A {
    private func foo() {}
    fileprivate func bar() {}

    func baz() {
        foo()
        bar()
    }
}

extension A {
    func test() {
        foo() // error: use of unresolved identifier 'foo'
        bar()
    }
}

let a = A()
a.foo() // error: 'foo' is inaccessible due to 'private' protection level
a.bar()
  • The private foo method is accessible only within the scope of the class A { ... } definition. It is not even accessible from an extension to the type.

  • The file-private bar method is accessible from the same source file.