【问题标题】:What is behavior of private access control for swift class?swift类的私有访问控制的行为是什么?
【发布时间】:2015-12-09 17:39:45
【问题描述】:

我用 Xcode 7 GM Seed 的故事板尝试了这个:

import UIKit

public class C {
    let _secret = arc4random_uniform(1000)

    private func secret() -> String {
        return "\(_secret) is a secret"
    }

}
let c1 = C()
c1.secret()

这编译并给了我“秘密”。所以这扰乱了我对 Swift 类和对象的访问控制的理解。为什么会这样?

【问题讨论】:

  • 私人访问将实体的使用限制在其自己的定义源文件中。这一切都记录在 Swift 书籍的“访问控制”一章中。

标签: swift access-modifiers


【解决方案1】:

在 Swift 中,private 表示只能在您正在执行的同一源文件中访问。如果您的问题中的代码包含在文件 C.swift 中,并且您会尝试从另一个 Swift 文件访问 secret 方法,则会收到编译时错误。

您可以在official documentation 中阅读有关不同访问修饰符的更多信息。

【讨论】:

    【解决方案2】:

    Swift 4 更新答案:

    有两种不同的访问控制:fileprivateprivate

    fileprivate 可以从他们的整个文件中访问。

    private 只能从它们的单个声明和扩展中访问。

    例如:

    // Declaring "A" class that has the two types of "private" and "fileprivate":
    class A {
        private var aPrivate: String?
        fileprivate var aFileprivate: String?
    
        func accessMySelf() {
            // this works fine
            self.aPrivate = ""
            self.aFileprivate = ""
        }
    }
    
    // Declaring "B" for checking the abiltiy of accessing "A" class:
    class B {
        func accessA() {
            // create an instance of "A" class
            let aObject = A()
    
            // Error! this is NOT accessable...
            aObject.aPrivate = "I CANNOT set a value for it!"
    
            // this works fine
            aObject.aFileprivate = "I CAN set a value for it!"
        }
    }
    

    更多信息,请查看Access Control Apple's documentation,也可以查看this answer

    【讨论】:

      猜你喜欢
      • 2016-03-28
      • 1970-01-01
      • 1970-01-01
      • 2012-10-06
      • 2014-04-02
      • 1970-01-01
      • 2012-02-28
      • 2015-08-01
      • 1970-01-01
      相关资源
      最近更新 更多