这article有助于理解Swift 3
中的新访问说明符.文中还举例说明了fileprivate
和private
的不同用法.
我的问题是——在一个只在这个文件中使用的函数上使用fileprivate
和使用private
不一样吗?
这article有助于理解Swift 3
中的新访问说明符.文中还举例说明了fileprivate
和private
的不同用法.
我的问题是——在一个只在这个文件中使用的函数上使用fileprivate
和使用private
不一样吗?
fileprivate
是以前的private
在同一个源文件中定义了扩展名的情况下,同一类型的扩展名可以访问类型内的Swift 4,个私有声明.
示例(全部在一个源文件中):
class A {
private func foo() {}
fileprivate func bar() {}
func baz() {
foo()
bar()
}
}
extension A {
func test() {
foo() // Swift 3: error: use of unresolved identifier 'foo'
// Swift 4: no error because extension is in same source file
bar()
}
}
let a = A()
a.foo() // error: 'foo' is inaccessible due to 'private' protection level
a.bar()
private foo
方法只能在
file private bar
方法可以从同一源文件访问.
Notes:
提案SE-0159 – Fix Private Access Levels建议恢复Swift 4中的Swift 2语义.在对swift evolution邮件列表进行了长时间且有争议的讨论后,该提案获得rejected票.
建议SE-0169 – Improve Interaction Between private Declarations and Extensions建议private