Mozahler
Mozahler

Reputation: 5303

In Swift, how do I make private variables visible to code in an extension which is in a separate file?

I took some legacy code I did not write, splitting a large view controller pretty much evenly into two portions. The main one contains everything but the callbacks from the ui, and all the callbacks were moved into an extension. I did all this in one file, which made it easy to do.

However, when I created the second file and moved the extension code to it there was one messy detail. Once half the code was moved into a separate file, things broke. Methods in the extension couldn’t use the private properties defined in the main file. How do make a property available to only other elements of the same class, even if parts of the class are in another file? My workaround is to not have any private variables, which isn't ideal.

Upvotes: 3

Views: 3709

Answers (2)

Nick Kohrn
Nick Kohrn

Reputation: 6049

I would suggest adding the code from the two separate files back into the same file. There's nothing wrong with having the main declaration of a type, along with any extensions of that type, in the same file. This allows you to use fileprivate for anything that you want to be private, such as variables, but anything that is in the same file can access them.

Update

As OOPer mentions in this answer, fileprivate can be replaced with private as of SE-0169.

Upvotes: 1

OOPer
OOPer

Reputation: 47896

Check these two Swift Evolution proposals already implemented in Swift 4

SE-0025 Scoped Access Level

SE-0169 Improve Interaction Between private Declarations and Extensions

Since SE-0025 was accepted and implemented, an extension cannot access private members of the extended type.

SE-0169 loosened this rule a little, but the extension still needs to be in the same source file of the original type definition, to access private members.

My workaround is to not have any private variables

That's one practical solution for your issue, or else you may need to move all extensions accessing private members into the same source file.

Upvotes: 1

Related Questions