微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

swift – 为什么私有扩展无法访问?

这是我的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会话中提到),然而,编译器告诉我:

‘myInt’ is inaccessible due to ‘private’ protection level

它与文档中提到的内容不兼容吗?

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

fileprivate var myInt = 10

但我想知道为什么它会像这样,我误解了文档中提到的内容?或者它是一个“Xcode”错误(使用9.0.1版本)?

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

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

如果项目已在Xcode 8(使用Swift 3)中创建,那么
Xcode 9将以“Swift 3模式”打开它,并将“Swift语言版本”设置为“Swift 3.2”.因此更严格的Swift 3限制.

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

更好的是,使用“编辑 – >转换 – >到当前的Swift语法……”

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐