如何为此函数添加完成处理程序?

时间:2016-01-07 18:56:02

标签: ios swift

我目前有一个功能,如果条件不满足就会调用自己的功能(效果非常好)但现在我想为它添加一个completionHandler,我已经尝试过但不同的方法但是我所尝试过的任何方式都不会归还完成 的 runSearch()

func runSearch(){
    search{
        _ in
        if (parResults.count < 20 && self.searchCounter < 20){
            self.runSearch()//Run search again**
        }
        if (parResults.count >= 20 && self.searchCounter < 20){
            self.searchComplete = true
        }
    }
}

我尝试了什么

带有completionHandler调用的

runSearch()

self.runSearch{
  msg in
print("all done") //Not executed
}

runSearch()with completionHandler func 1

func runSearch(completionHandler: (Bool) -> ()) -> () {
    search{
        _ in
        if (parResults.count < 20 && self.searchCounter < 20){
            self.runSearch{
                _ in
            }
        }
        if (parResults.count >= 20 && self.searchCounter < 20){
            self.searchComplete = true
            completionHandler(true)// Never returned
        }

    }
}

runSearch()with completionHandler func 2

 func runSearch(completionHandler: (Bool) -> ()) -> () {
    search{
        _ in
        if (parResults.count < 20 && self.searchCounter < 20){
            self.runSearch{
                _ in
                if (parResults.count >= 20 && self.searchCounter < 20){
                    self.searchComplete = true
                    completionHandler(true)//Not returned
                }
            }
        }
        if (parResults.count >= 20 && self.searchCounter < 20){
            self.searchComplete = true
        }

    }
}

2 个答案:

答案 0 :(得分:2)

您需要将每个新来电的completionHandler向下传递到runSearch

func runSearch(completionHandler: (Bool) -> ()) {
    search{
        _ in
        if (parResults.count < 20 && self.searchCounter < 20){
            self.runSearch(completionHandler) // <-------
        } else if (parResults.count >= 20 && self.searchCounter < 20){
            self.searchComplete = true
            completionHandler(true)
        }
    }
}

答案 1 :(得分:1)

func runSearch(completionHandler: (Bool) -> ()) -> () {
    search{
        _ in
        if (parResults.count < 20 && self.searchCounter < 20){
            self.runSearch(completionHandler)
        }
        if (parResults.count >= 20 && self.searchCounter < 20){
            self.searchComplete = true
            completionHandler(true)// Never returned
        }
        if (parResults.count == 0 && self.searchCounter == 20){
            self.noResultsFound = true
            completionHandler(true) //Never returned
        }
        if (parResults.count != 0 && self.searchCounter == 20){
            self.searchComplete = true
            completionHandler(true) // Never returned
        }
    }
}