AntiMoron
AntiMoron

Reputation: 1366

Access private property successfully in the same file but failed to use private inner class in swift

Here is my code:

public class TestPublic{
    internal class TestInternal{
        private class TestPrivate{
            private var x = 123
        }
        func foo()
        {
            print(TestPrivate().x)
        }
    }
}

let x = TestPublic()                        
let y = TestPublic.TestInternal()           
let z = TestPublic.TestInternal.TestPrivate() // This trigger an access error!!!
y.foo() // After removing last line.Everything compiles well and output '123'

The guide book of swift 2.0 said:

“Private access restricts the use of an entity to its own defining source file. Use private access to hide the implementation details of a specific piece of functionality.”

Now I wrote all these codes inside one single file.

TestPrivate.xshould be visible to TestInternal.foo.And this is ok for now.

But the wired thing is when I try to use the private inner class to create an instance it failed compiling! Is this a bug?

Upvotes: 0

Views: 39

Answers (1)

AntiMoron
AntiMoron

Reputation: 1366

This is not a bug.

private let z = TestPublic.TestInternal.TestPrivate() 

This would make it compile.

Without private indicator z can expose private class to other files for its access control is internal by default.

And this is how swift control accesses strictly.

Upvotes: 2

Related Questions