Solve this completion Block

情到浓时终转凉″ 提交于 2020-01-06 05:36:07

问题


i'm try to solve this completion block, but I keep having many warning.

Xcode give me warning

Cannot convert return expression of type '()' to return type '[AirportModel]'

Sorry I'm a beginner... little lost on this closure...

I have to return this vector of AirportModel in order to be display in a list in swiftUI, I want use DispatchQueue in order to avoid to block the view while searching:

func filter (valoreSearhed: String, arrayTosearh: AirportVector, completionBlock: (_ airports: [AirportModel]) -> Void) -> [AirportModel]  {
    DispatchQueue.global().async {
        let results  = arrayTosearh.filter { $0.aptICAO.localizedCaseInsensitiveContains(valoreSearhed) }
        completionBlock(results)
    }
}

回答1:


The problem isn’t the closure.

The problem that you’ve defined this filter method to return an [AirportModel], but it doesn’t. Get rid of that -> [AirportModel] at the end of the function declaration. You’re not returning anything from this function. You’re using the completion handler to pass the results back.


By the way, don’t forget to mark your closure as @escaping, too.




回答2:


I assume by intention it should return temporary empty array, so I'd recommend the following

func filter (valoreSearhed: String, arrayTosearh: AirportVector, completionBlock: @escaping (_ airports: [AirportModel]) -> Void) -> [AirportModel]  {
    DispatchQueue.global().async {
        let results  = arrayTosearh.filter { $0.aptICAO.localizedCaseInsensitiveContains(valoreSearhed) }
        completionBlock(results)
    }
    return []
}


来源:https://stackoverflow.com/questions/59596993/solve-this-completion-block

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!