4

As per swift documentation, If you define a type’s access level as private or file private, the default access level of its members will also be private or file private

I had created a sample code to analyse above statement using Swift 5.0

private class Profile {
    var name: String?
    //By default name should have private access level implicitly
}

private class Person {
    private var name: String?
    //name should have private access level explicitly
}

func gobalTestFunction() {
    let profile = Profile()
    let profileName = profile.name
    //This does not give any error and name is accessible here

    let person = Person()
    let personName = person.name
    //This gives error 'name' is inaccessible due to 'private' protection level
}

Expected Result:

While creating profileName there should be an error similar to the error which occur while creating personName

'name' is inaccessible due to 'private' protection level

Actual Result:

While creating personName error occurs but while creating profileName no error encountered.

rmaddy
  • 314,917
  • 42
  • 532
  • 579
Anmol Suneja
  • 97
  • 11
  • 4
    Possible duplicate of https://stackoverflow.com/a/43504968 – A top-level `private` class is actually `fileprivate`. – Martin R Oct 16 '19 at 06:51

1 Answers1

3
  • To make a class accessible within target/framework and not outside that, you can use default internal access modifier.
  • And if you want to make the class accessible within the file, you can use fileprivate access modifier.


    In short, Making a class private at top-level does not make sense. And it's actually file private.

    Thanks @Martin R for your useful comment.

Anmol Suneja
  • 97
  • 11