Does the `private` Access Control for the Custom Type works?

According to the Swift Programming Language Book from Apple, a Custom Type have the default private class member by defining the type's access level as private, as shown below.

class AccessControlTest {
    private let explicit = ExplicitPrivate()
    private let implicit = ImplicitPrivate()

    func printExplicit() {
        print(explicit.data) // 'data' is inaccessible due to 'private' protection level
        explicit.printExplicit() // 'printExplicit' is inaccessible due to 'private' protection level
}

    func printImplicit() {
        print(implicit.data) // Is it possible?
        implicit.printImplicit() // Is it possible?
    }
    
    class ExplicitPrivate {
        private var data = "explicit private"
        private func printExplicit() { print(data) }
    }
    
    private class ImplicitPrivate {
        var data = "implicit private"
        func printImplicit() { print(data) }
    }
}

let accessTest = AccessControlTest()
accessTest.printExplicit()
accessTest.printImplicit()

result ---

implicit private
implicit private

However, the default access level for private doesn't seem to work. You can see it with the ImplicitPrivate class.
Is there anyone who can explain this to me?

This is not true, and a known error in the text of The Swift Programming Language. The implicit access level of all members is internal, and their effective visibility is bounded by the visibility of the containing type.

3 Likes

I've got it, thanks! :slight_smile:

Terms of Service

Privacy Policy

Cookie Policy