问题
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