Home » Swift » Swift 2 internal vs private

Swift 2 internal vs private

Posted by: admin November 29, 2017 Leave a comment

Questions:

I’m confused about the internal and private access modifier.

The docs says:

“Internal access enables entities to be used within any source file
from their defining module, but not in any source file outside of that
module. You typically use internal access when defining an app’s or a
framework’s internal structure.”

How I thought it was, was that with internal you can access everything if you are in your own app. But this is not true, because when I have a viewcontroller what is default internal and I’m having a internal function on that viewcontroller I can’t access this from another file in another group (You create these in xCode).

What I tried was having a ViewController that has a method foo in group A then in group B I created a ViewController like this:

let vc: FakeViewController = FakeViewController()
vc.foo()

So is internal restricted to the same group? Or I’m I interpreting it wrong?

Is it useful that in a viewcontroller you create private methods and vars/lets?

Answers:

Internal access restricts access to the files within a singular application or framework.

Private restricts access to the individual source file that your object is created in.

See this link for a more in-depth explanation.

Overall, if your “Group A” and “Group B” are in the same application or framework, you should be able to access the methods from each, assuming the viewController allows internal access.

Questions:
Answers:

Suppose you have 3 different view controller source files A, B, C
then
In Private:- If Intancses in A are Private than only A’s Methods can use them
In Internal :- IF A is as Internal than B and C can easily use them.
Here is an example:
enter image description here

Thanks

Questions:
Answers:

My understanding is that private won’t allow the variable from being accessed from outside that class. However, there are times, like with gesture recognizers, you can’t make them private because they are needed behind the scenes. Marking them as “internal” lets them be accessed from within other functions, but not called directly.

Mostly I use internal to keep my code organized, so I know that’s not a public facing function but it can still be used.

Leave a Reply

Your email address will not be published. Required fields are marked *