在Swift3中区分fileprivate和private的好例子是什么 [英] What is a good example to differentiate between fileprivate and private in Swift3

查看:21
本文介绍了在Swift3中区分fileprivate和private的好例子是什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这篇文章有助于理解 Swift 3 中的新访问说明符.它还给出了fileprivateprivate 的不同用法的一些示例.

This article has been helpful in understanding the new access specifiers in Swift 3. It also gives some examples of different usages of fileprivate and private.

我的问题是 - 在仅在此文件中使用的函数上使用 fileprivate 是否与使用 private 相同?

My question is - isn't using fileprivate on a function that is going to be used only in this file the same as using private?

推荐答案

fileprivate 现在是之前的 privateSwift 版本:可从相同的源文件.标记为 private 的声明现在只能在它声明的词法范围内访问.所以 privatefileprivate 限制更多.

fileprivate is now what private used to be in earlier Swift releases: accessible from the same source file. A declaration marked as private can now only be accessed within the lexical scope it is declared in. So private is more restrictive than fileprivate.

Swift 4 开始, 类型内的私有声明可以被相同类型的扩展访问,如果扩展是在同一个源文件中定义的.

As of Swift 4, private declarations inside a type are accessible to extensions of the same type if the extension is defined in the same source file.

示例(全部在一个源文件中):

Example (all in one source file):

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()

  • 私有 foo 方法只能在以下范围内访问class A { ... } 定义.它甚至无法从类型的扩展(在 Swift 3 中,请参阅下面的第二个注释以了解Swift 4 中的更改).

    • The private foo method is accessible only within the scope of the class A { ... } definition. It is not even accessible from an extension to the type (in Swift 3, see the second note below for changes in Swift 4).

      文件私有的 bar 方法可以从同一个源文件中访问.

      The file-private bar method is accessible from the same source file.

      注意事项:

      1. 提案 SE-0159 – 修复私有访问级别 建议在 Swift 4 中恢复到 Swift 2 语义.经过对 swift-evolution 邮件列表的冗长且有争议的讨论,该提案是 被拒绝.

      1. The proposal SE-0159 – Fix Private Access Levels suggested to revert to the Swift 2 semantics in Swift 4. After a lengthy and controversial discussion on the swift-evolution mailing list, the proposal was rejected.

      提案SE-0169 – 改进私有声明和扩展之间的交互 建议将 private同一类型的扩展可访问的类型内的声明如果扩展名是在相同的源文件中定义的.这个提议在 Swift 4 中被接受并实现了.

      The proposal SE-0169 – Improve Interaction Between private Declarations and Extensions suggests to make private declarations inside a type accessible to extensions of the same type if the extension is defined in the same source file. This proposal was accepted and implemented in Swift 4.

      这篇关于在Swift3中区分fileprivate和private的好例子是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆