在 Swift 4 中,由于 nowprivate
在同一个源代码文件中的扩展中也是可见的,它与fileprivate
访问修饰符有何不同?
背景:在 Swift 3 中,类中的私有变量在同一个文件的扩展中是不可见的。为此,fileprivate
不得不使用。
在 Swift 4 中,由于 nowprivate
在同一个源代码文件中的扩展中也是可见的,它与fileprivate
访问修饰符有何不同?
背景:在 Swift 3 中,类中的私有变量在同一个文件的扩展中是不可见的。为此,fileprivate
不得不使用。
文件私有
文件私有访问将实体的使用限制在其自己的定义源文件中。当在整个文件中使用这些细节时,使用文件私有访问来隐藏特定功能的实现细节。
语法: fileprivate <var type> <variable name>
示例: fileprivate class SomeFilePrivateClass {}
Private
私有访问将实体的使用限制为封闭声明,以及同一文件中该声明的扩展。当这些细节仅在单个声明中使用时,使用私有访问来隐藏特定功能的实现细节。
语法: private <var type> <variable name>
示例: private class SomePrivateClass {}
以下是有关所有访问级别的更多详细信息:Swift - Access Levels
回答您的问题:( 在 Swift 3 中,类中的私有变量在同一文件的扩展中不可见。为此,必须使用 fileprivate。)
是的,在 Swift 4.0 中,Private 现在可以在扩展中访问,但在同一个文件中。如果您在其他文件中声明/定义扩展名,那么您的扩展名将无法访问您的私有变量
看这个图像:
文件: ViewController.swift
这里扩展和视图控制器都在同一个文件中,因此私有变量testPrivateAccessLevel
可以在扩展中访问
文件: TestFile.swift
这里扩展和视图控制器都在不同的文件中,因此私有变量testPrivateAccessLevel
在扩展中是不可访问的。
这里的类ViewController2
是一个子类,ViewController
两者都在同一个文件中。这里私有变量testPrivateAccessLevel
在子类中不可访问,但 fileprivate 在子类中可访问。
适用于 swift 4.0 及其版本
Private
Private 仅在类及其扩展名中访问(当扩展名在同一个 .swift 文件中时)。
文件私有
文件-仅在类及其扩展名和子类中的私有访问(当扩展名或子类在同一个 .swift 文件中时)。
///////////////ViewController1.swift file
class ViewController1 {
private func testPrivate() {
print("testPrivate")
}
fileprivate func testFilePrivate() {
print("testFilePrivate")
}
func doesNothing1() {
testPrivate() //success
testFilePrivate() //success
}
}
extension ViewController1 {
func doesNothingInExtensionSameFile() {
testPrivate() //success
testFilePrivate() //success
}
}
class SomeOtherClassInSameFile {
let vc1 = ViewController1()
func doesNothing() {
vc1.testPrivate() //throws error
vc1.testFilePrivate() //success
}
}
////////////// ViewController2.swift file
extension ViewController1 {
func doesNothingInExtensionDifferentFile() {
testPrivate() //throws error
testFilePrivate() //throws error
}
}
公开与公开:
除上述之外,两者都是相同的。
私有与文件私有:
除上述之外,两者都是相同的。
private and fileprivate access levels have come closer with Swift4.
The difference in access lies as follows:
fileprivate members - only & entirely within that .swift file
private members - only in that class & extension of the class if both are present in same .swift file
Hence only fileprivate members(not private) can be accessed in
“Private”只能在类中访问,“FilePrivate”只能在 .swift 文件中访问。
Private:类和类扩展中的访问。FilePrivate : 在类、子类、扩展中访问,