【问题标题】:How to use an array from another class Swift如何使用另一个类 Swift 中的数组
【发布时间】:2020-07-25 16:11:06
【问题描述】:

这里有点进退两难。我的方法 GetData() 在 jsondata1 中存储了一个数组。我将如何在另一个类中使用该数组?我已经将它设置为 Data 的子类。谢谢!

class Data {

    let parameters = ["test": ViewController().myinfo]


    func GetData() {  
        AF.request("my url", parameters: parameters).responseDecodable(of: Array<JsonData>.self ) { (response) in
            let jsondata1 = response.value
            // debugPrint(response)
            print(jsondata1)
        }
    }
}



class Testing : Data {

    func AnnualTesting() {
    
        //How would I reference jsondata1 here?
        debugPrint(jsondata1)
    }
}
    

【问题讨论】:

  • 您根本没有“存储”数据。你正在打印它并把它扔掉。
  • 在使用 json 和异步调用(如 AF.request)之前,我认为您需要先了解类和结构的基础知识,以及如何启动它们以及在对象之间传递数据等等。这个问题有很多问题,所以我认为它太宽泛而没有意义。

标签: swift inheritance


【解决方案1】:

一些事情...见 cmets。

class Data {

    // This kind of thing is the source of more bugs than I can count.
    // Are you *sure* you want to create a brand new ViewController that's connected to nothing?
    let parameters = ["test": ViewController().myinfo]

    // Declare an instance variable so it's visible to the subclass
    // (Not sure what data type you want to use here.  I'm calling it a String for convenience.)
    var jsondata1: String?  

    func GetData() {
        AF.request("my url", parameters: parameters).responseDecodable(of: Array<JsonData>.self ) { (response) in

            // Note that this is filled in asynchronously,
            // so isn't available as soon as the function is called.
            // Currently you have no way of knowing in other code when the result *is* available.
            self.jsondata1 = response.value

           // debugPrint(response)
            print(jsondata1)
        }
    }

}

class Testing : Data {

    func AnnualTesting() {
        
        //How would I reference jsondata1 here?
        debugPrint(jsondata1 ?? "Nothing to see here")
    }

}

【讨论】:

    【解决方案2】:

    您对 jsondata1 的声明在某个块的范围内。 从外面看不到。

    你必须在类的接口中声明它, 就像你对变量“参数”所做的那样。

    一般来说,如果它在接口中声明,您可以从另一个类访问变量。它可以声明为实例变量或静态(类)变量。而且你应该有类的实例来访问实例变量,而不应该有实例来访问类/静态变量。

    或者像你一样,通过继承。

    【讨论】:

      猜你喜欢
      • 2016-06-05
      • 2021-02-24
      • 2015-12-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多