gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-30 23:13:49 24 4
gpt4 key购买 nike

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

enter image description here

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

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


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

fileprivate var myInt = 10

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

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

最佳答案

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

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

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

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

关于swift - 为什么扩展程序无法访问 private?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46871551/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com