gpt4 book ai didi

swift - 返回完成处理程序后重新执行 while 循环

转载 作者:搜寻专家 更新时间:2023-11-01 07:28:33 25 4
gpt4 key购买 nike

我有一个 while 循环,如果返回的数字为 0,我希望继续执行。目前的问题是循环永远不会停止,因为它不等待完成处理程序返回其结果(这需要几秒钟) .如何在 if 语句完成后才重新执行 while 循环?

while 循环

var empty = true
override func viewDidLoad() {
repeat {
str = iFunctions.generateRandomStringWithLengthOf(4) as String
iFunctions.getServerData(str){(msg)
in
if (msg > 0){
self.empty = false
print("not empty")
}
else{
print("empty")
}
self.count = msg!
print(self.count)

}
} while(empty)
}

函数

func getServerData(q: String, completionHandler: (Int?) -> ()) -> () {
let params = [
"term": q
]
Alamofire.request(.GET, "URL", parameters: params)
.responseJSON { response in
if response.result.error == nil {
let json = JSON(response.result.value!)
//add data to struct
completionHandler(json["results"].count)
}
}

}

最佳答案

你不应该用循环来做这件事。这就是 Alamofire 的全部意义所在,因此您不必处理线程和循环。您正在使用高级指令:回调。

其实很容易解决你的问题:

var empty = true
override func viewDidLoad() {
self.tryGettingDataFromServer()
}

func tryGettingDataFromServer(){
str = iFunctions.generateRandomStringWithLengthOf(4) as String
iFunctions.getServerData(str){(msg) in
if (msg > 0){
self.empty = false
print("not empty")
}
else{
// The closure keeps a reference to self and calls
// the tryGettingDataFromServer again if "empty"
// It will happen infinitely until "not empty"
self.tryGettingDataFromServer()
}
self.count = msg!
print(self.count)
}

}

关于swift - 返回完成处理程序后重新执行 while 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34275862/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com