在我回顾 Swift 中的存储库项目后,我意识到存在一个代码问题,我很难找出与 MKLocalSearch 特定函数的 API 更改相关的错误
具体来说,在我的下面的代码片段中,主要包含函数,基本上执行搜索并更新到搜索位置
func searchBarSearchButtonClicked (_ searchBar: UISearchBar){
//here check if local search existed, it then cancel the search
if let search = localSearch {
search.cancel()
}
let request = MKLocalSearchRequest()
request.naturalLanguageQuery = searchBar.text
localSearch = MKLocalSearch(request: request)
//set the network activity visible
UIApplication.shared
.isNetworkActivityIndicatorVisible = true
//start the search and deliver the response with error handling asynchronously
/* --------------------------This is where the bug occurs --------------*/
localSearch!.start {
[weak self] (response : MKLocalSearchResponse?, error: NSError?) in
if error != nil {
return
}
UIApplication.shared.isNetworkActivityIndicatorVisible = false
//safely extract location search results based on response
guard let myResponse = response else {
print("error in search: \(error?.localizedDescription ?? MissingError)")
return
}
// guard let location = myResponse.mapItems.first else {
// print("There are no results")
// return
// }
guard let location = myResponse.mapItems else{
print("There are no results")
return
}
self?.updateMapWithItem(location, region: myResponse.boundingRegion)
}
所以我收到了错误及其完整消息
Cannot convert value of type '(MKLocalSearchResponse?, NSError?) -> ()' to expected argument type 'MKLocalSearchCompletionHandler' (aka '(Optional<MKLocalSearchResponse>, Optional<Error>) -> ()')
Swift 3.0 编译器建议我执行以下操作,但它的解决方案完全足够,因为它只是不断告诉我插入越来越多的以下语句,而没有完全解决问题。
Insert ' as! MKLocalSearchCompletionHandler'
我实际上想将整个项目代码从 Swift 2.x 迁移到 4.0,但我的意思是我需要先弄清楚从 2.x 到 3.0 的迁移。
最佳答案
使用
localSearch?.start(completionHandler: {
[weak self] (response, error) in
....
})
而不是
localSearch!.start {
[weak self] (response : MKLocalSearchResponse?, error: NSError?) in
....
}
关于swift - 从 Swift 2.x 到 4.0 的代码迁移问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48657205/