swift - 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!
解决方案
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.
推荐阅读
- javascript - 如何通过不在引号中的正则表达式拆分文本
- python - 如何在python中编辑矩阵中的值?
- ascii - 为什么 '[' 和 ']' ASCII 码不相互跟随?
- python - OSError: [WinError 126] 未找到模块
- javascript - Github 网页外部 css 无法正常工作,但 js 工作正常
- docker - Nuxt.js SSR w/ Nest API 在 Docker 容器中部署到 AWS
- android - 如何在flutter中使用fxpoi包读取CSV文件
- python - 使用 keras 将图像划分为子部分
- python - Python同时监听和分析数据
- python-3.x - Pandas 对条形图进行分组和重采样: