首页 > 解决方案 > how can i call return array from Swift class to swiftui view file

问题描述

My function in class page; soru an object and [soru] an array list.

func GetSorular()->[Soru] {
    NetworkManager.instance.fetch(HTTPMethod.get, url: "https://app.kivacrm.com/api/v1/data/osym/sorular" , requestModel: nil, model: SorularResponse.self ) { response in
        switch(response)
        {
            case .success(let model):
                let sorularModel = model as! SorularResponse
                for soru in sorularModel.records {
                    self.sorularArray.append(soru)
                }
            
        case .failure(_):
            print("Failure e girdi!")
        }
    }
    print("results:\(sorularArray)")
    return sorularArray
}

return result empty..

the printing and viewpage getting result is unfortunately blank;

results:[]
count Sorular :0

in View code:

var sorular=DerslerController().GetSorular();

Please Help!

标签: swift

解决方案


You can't structure your code the way your are trying to. Your NetworkManager's fetch() method is asynchronous. It returns immediately, and the closure you pass to it gets executed at some point later, after your GetSorular() function has already returned without appending anything to your array. Instead, you need to refactor your GetSorular() to take a completion handler.

Your code might look like this: (Note that in Swift function names should start with a lower case letter.)

//Instead of trying to return the results, take a completion handler
func getSorular(completion: @escaping ([Soru])->() ) {
    var resultsArray = [Soru]()
    NetworkManager.instance.fetch(HTTPMethod.get, url: "https://app.kivacrm.com/api/v1/data/osym/sorular" , requestModel: nil, model: SorularResponse.self ) { response in
        switch(response)
        {
            case .success(let model):
                let sorularModel = model as! SorularResponse
                for soru in sorularModel.records {
                    resultsArray.append(soru)
                }
            print("results:\(resultsArray)")
        case .failure(_):
            print("Failure e girdi!")
        }
        completion(resultsArray)  //Instead of trying to return the results, pass them to the completion handler
    }
}

Then you'd call the function like this:

getSorular { results in
    self.sorularArray.append(contentsOf: results)
    //Do whatever else you need to do with your sorularArray
}

I refactored the code so it builds a local array and returns it rather than appending to a global array. That is much safer.


推荐阅读