swift - 从 Swift 2.x 到 4.0 的代码迁移问题

标签 swift migration mapkit

在我回顾 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/

相关文章:

ios - 子类化 MKMapView 并使其成为 mapview 委托(delegate),同时仍然允许其他委托(delegate)

ios - 动态 MapPin 图像无法正确缩放 IOS 8 Swift

swift - 实际上,如何在 Xcode 中使用一条横跨整个屏幕的垂直线分隔两个部分

ios - 在 FOR 循环中创建和设置 UIButton 的标题会中断循环

c++ - 测试从 qt4 迁移到 qt5 的库时出现段错误

mysql - 将 MySQL 数据从 Yes/No varchar 迁移到位字段

swift - tableview controller 底部奇怪的灰色区域

swift - 用 Moya 处理缓存

MySQL 到 postgreSQL 迁移

ios - 检测 mkoverlay 上的触摸