1

in this example getInstance is public so it makes sense to be accessible but the private variable was accessible as well, why?

public class SingleObject {

    public struct Static {

        private static var object: SingleObject?

        public static func getObject() -> SingleObject {
            if (object == nil) {
                object = SingleObject()
            }
            return object!
        }
    }

}

SingleObject.Static.object //why private is accessible here?

SingleObject.Static.getObject()
user2727195
  • 7,122
  • 17
  • 70
  • 118

3 Answers3

5

As of Swift 3, the example code no longer compiles. A new modifier called fileprivate was added and works the way private used to work (i.e. it can be seen by anything else in the same file).

private in Swift 3 and 4 now works more like you would expect it to - in Swift 3, it can only be accessed within the context it was declared in, while in Swift 4 it can also be accessed from extensions to that type (but only if they're in the same file).

John Montgomery
  • 6,739
  • 9
  • 52
  • 68
2

The private access modifier makes a declaration private to the file and not to the class or struct. That sounds a little weird, I know, but it's how it's implemented in swift.

The other 2 access modifiers are:

  • internal: accessible in the current module only
  • public: accessible from anywhere

Suggested reading: Access Control

Antonio
  • 71,651
  • 11
  • 148
  • 165
  • any explanation for this please http://stackoverflow.com/questions/27713835/compiler-forcing-self-inside-static-method-of-a-function-while-using-dispatch-sy – user2727195 Dec 30 '14 at 23:23
1

The private keyword means that the variable is only accessible within the same file not within the same class.

You are accessing the property from within the same file, which is why it is working. Try doing it from a different file and you will see that it is not accessible.

Abizern
  • 146,289
  • 39
  • 203
  • 257
  • Sorry to downvote, but this is incorrect. The fileprivate keyword will refer to a variable only accessible in the same file. But the private keywork will work inside of that class or struct. For example, an extension to a class will be able to access it from another file. – Alec O Mar 05 '18 at 16:10
  • 2
    @AlecO The curse of a moving language. My answer was correct at time of writing, and actually answered the question. – Abizern Mar 06 '18 at 17:53
  • @AlecO Swift 4: `private` keyword will not work if you are trying to access it from an extension at another file – Samman Bikram Thapa Jan 14 '19 at 23:33