swift class 的私有访问控制行为是什么?
What is behavior of private access control for swift class?
我用 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()
这个编译给了我"secret"。所以这打乱了我对 Swift class 和对象的访问控制的理解。为什么会这样?
In Swift private
表示只能在您正在执行的同一源文件中访问。如果您问题中的代码包含在文件 C.swift
中,并且您尝试从另一个 Swift 文件访问 secret
方法,您将遇到编译时错误。
您可以在 official documentation 中阅读有关不同访问修饰符的更多信息。
Swift 4 更新的答案:
有两种不同的访问控制:fileprivate和private .
fileprivate 可以从他们的整个文件中访问。
private 只能从它们的单个声明和扩展中访问。
例如:
// 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!"
}
}
有关详细信息,请查看 Access Control Apple's documentation, Also you could check this answer。
我用 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()
这个编译给了我"secret"。所以这打乱了我对 Swift class 和对象的访问控制的理解。为什么会这样?
In Swift private
表示只能在您正在执行的同一源文件中访问。如果您问题中的代码包含在文件 C.swift
中,并且您尝试从另一个 Swift 文件访问 secret
方法,您将遇到编译时错误。
您可以在 official documentation 中阅读有关不同访问修饰符的更多信息。
Swift 4 更新的答案:
有两种不同的访问控制:fileprivate和private .
fileprivate 可以从他们的整个文件中访问。
private 只能从它们的单个声明和扩展中访问。
例如:
// 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!"
}
}
有关详细信息,请查看 Access Control Apple's documentation, Also you could check this answer。