Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is not common the use of Private properties/methods in Swift

First of all let me tell you that I just started playing around with Swift and haven't really seen a lot of code written in it but all of the tutorials I have seen they don't use private as in some other languages and as I understand Swift has three access controls, Private, Public and Internal, with Internal being the default.

I'm a little confused and despite the fact that I don't have a lot of programming experience in general but my understanding was that in a program you make everything private and only make public the properties and methods that you want to expose to other classes.

From Apple Docs

In addition to offering various levels of access control, Swift reduces the need to specify explicit access control levels by providing default access levels for typical scenarios. Indeed, if you are writing a single-target app, you may not need to specify explicit access control levels at all.

To me by leaving every property/method as the default (Internal) you are basically giving access to other classes to their values, correct?

Why is that in Swift/Cocoa you rarely see the use of the Private accessor for properties that you don't want other parts of your program to have access?

Can someone be so kind and explain the concept accessors in general and why is Swift designed this way, or even better correct me if I'm wrong in the assumption I'm making above, again I don't have to much experience in OOP and I may be confused on the concept of accessors in general.

Thanks

Update: Today (01/07/2016) I watched video #3 Applying MVC from the course Developing iOS 8 Apps with Swift offered by Stanford University in iTunes and in minute 24:15 Paul Hegarty talks about access control, I highly recommend it.

like image 582
fs_tigre Avatar asked Nov 22 '15 01:11

fs_tigre


1 Answers

Access control in Swift was one of the things that surprised me as well, so you are not alone. Swift uses a paradigm quite different from that used by C++, Java, C# that I was previously familiar with.

Swift's access control is not based on classes, but on source files and modules. The idea is that if you write a class, then you should have access to all of its members from another class in the same source file or module by default. If someone else extends your class, their code will be in a different module and source file, so they won't be able to access your base class members unless you give them access.

If you think about it, Swift paradigm of access control makes as much sense as that of C++/Java, it's just different.

Please see http://www.swiftprogrammer.info/swift_vs_cpp.html for this and other differences between the languages.

like image 97
Anatoli P Avatar answered Nov 14 '22 23:11

Anatoli P