代码之家  ›  专栏  ›  技术社区  ›  crypt

Swift 4中private和fileprivate的区别是什么

  •  12
  • crypt  · 技术社区  · 7 年前

    在Swift 4中,从现在开始 private 在扩展中也可以在同一源代码文件中看到,它与 fileprivate

    背景: 文件专用

    7 回复  |  直到 7 年前
        1
  •  38
  •   Krunal    7 年前

    文件专用

    语法: fileprivate <var type> <variable name>
    fileprivate class SomeFilePrivateClass {}



    同一文件中的声明 . 当特定功能的实现细节仅在单个声明中使用时,使用私有访问来隐藏这些细节。
    语法: private <var type> <variable name>
    private class SomePrivateClass {}


    以下是有关所有访问级别的更多详细信息: Swift - Access Levels

    回答您的问题:

    是的,在Swift 4.0中,现在可以在扩展名中访问Private,但在同一个文件中。如果在其他文件中声明/定义扩展名,则扩展名将无法访问您的私有变量



    ViewController。敏捷的
    在这里,扩展名和视图控制器都在同一个文件中,因此是私有变量 testPrivateAccessLevel 可在扩展中访问

    enter image description here


    文件:
    在这里,扩展名和视图控制器都位于不同的文件中,因此是私有变量 testPrivateAccessLevel测试私人访问级别

    enter image description here

    enter image description here


    Here类 ViewController2 是的子类 ViewController testPrivateAccessLevel测试私人访问级别

    enter image description here

        2
  •  9
  •   Vaibhav Sharma    6 年前


    私有的
    仅在类及其扩展名中进行私有访问(当扩展名位于同一.swift文件中时)。

    文件专用

        3
  •  0
  •   jeevan eashwar    6 年前
    ///////////////ViewController1.swift file
            class ViewController1 {
                private func testPrivate() {
                    print("testPrivate")
                }
                fileprivate func testFilePrivate() {
                    print("testFilePrivate")
                }
                func doesNothing1() {
                    testPrivate() //success
                    testFilePrivate() //success
                }
            }
            extension ViewController1 {
                func doesNothingInExtensionSameFile() {
                    testPrivate() //success
                    testFilePrivate() //success
                }
            }
            class SomeOtherClassInSameFile {
                let vc1 = ViewController1()
                func doesNothing() {
                   vc1.testPrivate() //throws error
                   vc1.testFilePrivate() //success
                } 
            }
    ////////////// ViewController2.swift file
            extension ViewController1 {
                func doesNothingInExtensionDifferentFile() {
                    testPrivate() //throws error
                    testFilePrivate() //throws error
                }
            }
    
        4
  •  0
  •   vesirak    5 年前

    Swift4的访问级别更近了。

    文件专用 成员-仅限(&M);完全在这个范围内。swift文件

    私有的

    因此只有 文件专用 )可以在中访问

    • 类的实例(在另一个类中初始化)。swift文件。
        5
  •  0
  •   Neeraj Khede    4 年前

    • Public不允许在另一个类中继承一个类 模块/目标,而Open有。
    • 公共方法不允许在另一个 模块/目标,而Open有。

    私有与文件私有:

    • (在单个文件中)Private不允许访问子类中的(func和属性),而FilePrivate允许。
    • (文件外)Private和FilePrivate都无法访问。

    除此之外,两者都是相同的。

        6
  •  -2
  •   Aram Ispiryan    6 年前

        7
  •  -3
  •   Bilal Anwar    5 年前

    私有:类内访问和类扩展。 FilePrivate:在类、子类、扩展、,

    推荐文章