为什么扩展程序无法访问 private?

Why private is unaccessible to the extension?

这是我的 ViewController.swift 文件:

class ViewController: UIViewController {
    private var myInt = 10
}

extension ViewController {
    func printMyInt() {
        print(myInt)
    }
}

虽然在Swift documentation - Access Levels section中提到:

Private access restricts the use of an entity to the enclosing declaration, and to extensions of that declaration that are in the same file. Use private access to hide the implementation details of a specific piece of functionality when those details are used only within a single declaration.

自从 Swift 4 已经发布,我假设我能够实现这样的事情(它也在:What's New in Swift - WWDC 2017 session 中提到),然而,编译器告诉我:

'myInt' is inaccessible due to 'private' protection level

是否与文档中提到的内容不兼容?


作为一个简单的快速解决方案,我可以将其声明为:

fileprivate var myInt = 10

但我想知道为什么会这样,我是不是误解了文档中提到的内容?还是 "Xcode" 错误(使用 9.0.1 版本)?

备注:项目已经在较旧的Xcode8中创建,然后迁移 到 Xcode 9.

Swift 4 中,private 成员 可访问该声明的扩展同一个文件,参见 SE-0169 – Improve Interaction Between private Declarations and Extensions.

如果项目已在 Xcode 8 年创建(Swift 3 年),则 Xcode 9 将在 "Swift 3 mode" 中打开它并将 "Swift Language Version" 设置为 "Swift 3.2"。因此更严格的 Swift 3 限制成立。

要使私有扩展对同一文件中的扩展可见, 在构建设置中将 Swift 语言版本设置为 4。 (当然 这可能需要对您的代码进行更多更改。)

更好的是,使用"Edit -> Convert -> To Current Swift Syntax ..."