加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-14 02:24:35 所属栏目:百科 来源:网络整理
导读:这是我的ViewController. swift文件: class ViewController: UIViewController { private var myInt = 10}extension ViewController { func printMyInt() { print(myInt) }} 虽然如Swift documentation – Access Levels section中所述: Private access re
这是我的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语法……”

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读