【问题标题】:How to access fileprivate properties from another class?如何从另一个类访问文件私有属性?
【发布时间】:2020-05-05 19:43:43
【问题描述】:

据我了解,可以从同一个 .swift 文件中的另一个类访问 fileprivate 属性。

如何格式化此代码以消除“使用未解析的标识符'fileprivateProperty'”错误?

import Foundation

class FirstClass {

    fileprivate var fileprivateProperty = "This is a fileprivate property"

}

class SecondClass {

    init() {

        func printProperty() {
            print("\(fileprivateProperty)")
        }
    }
}

【问题讨论】:

  • 这与“fileprivate”属性无关。 fileprivateProperty 仍然是 FirstClass 的属性,而不是 SecondClass 的属性。
  • FirstClassSecondClass 的对象不相关。你可以想象这两个对象是HumanCar。你所做的相当于试图访问familyNameCar 对象。属于哪个人类?嗯,还不清楚。要求fileprivateProperty,而不要求FirstClass的特定对象的fileprivateProperty是没有意义的

标签: swift properties scope


【解决方案1】:

是的,你是对的,文件私有属性可以在 swift 文件中访问。但您仍然需要在访问其属性之前为第一类创建对象或引用。

import Foundation

class FirstClass {

fileprivate var fileprivateProperty = "This is a fileprivate property"

}

class SecondClass {

init() {

    func printProperty() {
        print("\(FirstClass().fileprivateProperty)")
    }
 }
}

像这样。

【讨论】:

    猜你喜欢
    • 2012-09-17
    • 2017-03-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多