Ian Newson Ian Newson - 8 months ago 25
Swift Question

Swift access control on computed properties: why does this work?

I seem to be misunderstanding something about access control modifiers in Swift. Here is my code from a playground:

class Something {
private (set) var name :String {
get { return "" }
set {}
var thing = Something();
thing.name = "";

My intuition and experience from other languages tells me that there should be a compiler error on the last line.

The book I'm learning from however states that private means the member being modified is only accessible from the same source file.

Am I safe to assume this scenario would generally be an error in most projects, and this is only because I'm running this code in a playground?

Is the statement that private members can only be accessed from the same source file totally accurate?


This rule is valid for all versions of Swift 2. It is valid for your example as well, and worked because your setter code is in the same file (if I understand your example correctly) in which the setter was invoked.

The top-level assignment expression thing.name = ""; was allowed because it is running in a playground. Outside playgrounds, this top-level assignment would be illegal.