Hi
Class scope with swift and Xcode now became little confusing for me, for classes we dont use the words private and purblic when
we define them anymore so my question is how to predict its scope, for example the ViewController file we add is it public for all the
application ? and if I define a class inside it will it be public by default to all the application ?
What if we define a class in its own file ? will it be public ? and is it better to define a class in its own file or inside a view controller ?
--
Kindest Regards
If you declare a class as private (or fileprivate), it will not be visible outside of itself (or its file).
Make the test:
- declare the FirstViewController as
class FirstViewController: NSViewController { }
Then in a SecondViewController class, try to create an instance of a FirstViewController
class SecondViewController: NSViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do view setup here.
let firstVC = FirstViewController()
}
This setup works.
Now, change by adding fileprivate
fileprivate class FirstViewController: NSViewController { }
You get a compile error:Use of unresolved identifier 'FirstViewController'
It is no more visible ouside of its file.
If you declare a property in a class as private (or fileprivate), you will not be able to access to it outside of the class (or outside of the file).
That is a good practice to declare most properties as private.
A good way: declare all properties as private.
Then, if you get a compile error of undeclared propertyX, remove the private attribute.
In addition, if you open the interface file (click in the button with the 4 small square at the top left of the panel with the ViewController code and select 'Counterpart' > file (interface)) : propertyX will not show anymore.
What if we define a class in its own file ? will it be public ?
If you don't add private or fileprivate, yes it will be public. And usually, that is what you have to do.
and is it better to define a class in its own file or inside a view controller ?
If the class is specific to the VC, it can be declared inside. But it is not a good practice to put classes (which are often data models) inside the VC. It is better to get them out.
They can be in the same file, but for better readibility, it is usually better to put them in a separate file.
Just be cautious to give very explicit names to files and classes, for making their use easier later on.
Hope that's clear.