0

I tried this with storyboard with Xcode 7 GM Seed:

import UIKit

public class C {
    let _secret = arc4random_uniform(1000)

    private func secret() -> String {
        return "\(_secret) is a secret"
    }

}
let c1 = C()
c1.secret()

This compiled and gave me the "secret". So this upsets my understanding of access control for Swift class and object. Why is this happening?

hennes
  • 9,147
  • 4
  • 43
  • 63
kawingkelvin
  • 3,649
  • 2
  • 30
  • 50
  • 2
    Private access restricts the use of an entity to its own defining source file. It is all documented in the Swift book, in the "Access Control" chapter. – Martin R Sep 13 '15 at 17:43

2 Answers2

3

In Swift private means accessible only within the same source file which is what you're doing. If the code in your question was contained in a file C.swift and you would try to access the secret method from another Swift file you would get a compile-time error.

You can read more about the different access modifiers in the official documentation.

hennes
  • 9,147
  • 4
  • 43
  • 63
2

Swift 4 Updated answer:

There are two different access controls: fileprivate and private.

fileprivate can be accessed from their entire files.

private can only be accessed from their single declaration and extensions.

For example:

// Declaring "A" class that has the two types of "private" and "fileprivate":
class A {
    private var aPrivate: String?
    fileprivate var aFileprivate: String?

    func accessMySelf() {
        // this works fine
        self.aPrivate = ""
        self.aFileprivate = ""
    }
}

// Declaring "B" for checking the abiltiy of accessing "A" class:
class B {
    func accessA() {
        // create an instance of "A" class
        let aObject = A()

        // Error! this is NOT accessable...
        aObject.aPrivate = "I CANNOT set a value for it!"

        // this works fine
        aObject.aFileprivate = "I CAN set a value for it!"
    }
}

For more information, check Access Control Apple's documentation, Also you could check this answer.

Ahmad F
  • 30,560
  • 17
  • 97
  • 143