-1

So I have a Swift file with some class Whatever. This class has a number of private properties. Like this:

class Whatever
{
    private let privateString = "Blabla"
    private let privateInt    = 125
    
    // a lot of code here
 }

I would like to create an extension for this class in a separate file. Just in order to avoid having a large file with enormous amount of code. But I can't. An extension in a separate file cannot access private properties of the class. So I'm forced to either make private properties internal or maintain a single large file. Is there any technical solution to this problem except creating a module for this functionality?

Andrey Chernukha
  • 21,488
  • 17
  • 97
  • 161
  • https://stackoverflow.com/a/61436772/5501940 – Ahmad F Feb 16 '22 at 10:30
  • I have no idea what all that “enormous amount of code” does but one way to break it down could be to make the functions static and pass the private properties as parameters from a non static function, then you could have the static functions with all the code in another file(s) and the calling functions in the main file – Joakim Danielson Feb 16 '22 at 12:06

2 Answers2

1

You can't access private properties from another files. The only thing I can think of that may help you is to use to replace private with private(set) which provide you a read-only access from other files.

Tal Sahar
  • 784
  • 1
  • 7
  • 10
  • Thank you for the response but this doesn't solve my problem. I need a separate file. And btw extensions in the same file can access private properties so you don't need fileprivate – Andrey Chernukha Feb 16 '22 at 10:12
  • 1
    Thanks for fixing me. What about declaring properties with `private(set)`? It doesn't solve your problem but may help. – Tal Sahar Feb 16 '22 at 10:19
  • Yep, that's better than nothing. Add this to your response and I will upvote it and if nobody comes up with something better I will accept it – Andrey Chernukha Feb 16 '22 at 10:22
0

This doesn't come up in iOS programming much, but I think a lot of iOS programmers know this instinctively, make you model classes just store values, and maybe some really basic methods on them, then you have model controllers that can modify the model classes, in Mac OS we always talked about model, model controllers, view controllers, and views, but in reality I think this was the model, view, control pattern and the model, view, presenter pattern combined, and model controls where the real controllers, and view controllers where the presents.

Nathan Day
  • 5,981
  • 2
  • 24
  • 40