在Swift3中区分文件私有和私有的好例子 [英] What is a good example to differentiate between fileprivate and private in Swift3

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

问题描述

文章已被有助于理解 Swift 3 中的新访问说明。它还给出了 fileprivate private 的不同用法的一些示例。

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 现在是早期
Swift版本中的 private :从
可以访问相同的源文件。现在只能在声明的词法范围内访问标记为 private 的声明。
所以 private fileprivate 更具限制性。

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 方法仅在
    范围内可访问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 –改善互动在私有声明和扩展名之间建议在定义了扩展名的类型相同的扩展名中访问私有
      类型的声明相同的源文件中。
      该建议已在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中区分文件私有和私有的好例子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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