本文介绍了"[CLPlacemark]?"不能转换为'[CLPlacemark]'->迅捷2的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我在StackOverflow上找到的代码的一部分.
它在Swift 1.2中工作为什么此代码在Swift 2中不再起作用了?

this is a part of code I found on StackOverflow.
It was working in Swift 1.2Why this code is not working anymore in swift 2:

geoCoder.reverseGeocodeLocation(location, completionHandler: { (placemarks, error) -> Void in
        let placeArray = placemarks as [CLPlacemark] // !!! ERROR HERE !!!

        // Place details
        var placeMark: CLPlacemark!
        placeMark = placeArray[0]

        // Address dictionary
        print(placeMark.addressDictionary)

        // Location name
        if let locationName = placeMark.addressDictionary["Name"] as? NSString {
            print(locationName)
        }

        // Street address
        if let street = placeMark.addressDictionary["Thoroughfare"] as? NSString {
            print(street)
        }

        // City
        if let city = placeMark.addressDictionary["City"] as? NSString {
            print(city)
        }

        // Zip code
        if let zip = placeMark.addressDictionary["ZIP"] as? NSString {
            print(zip)
        }

        // Country
        if let country = placeMark.addressDictionary["Country"] as? NSString {
            print(country)
        }

    })

错误是GetLocationViewController.swift:67:41:'[CLPlacemark]?' is not convertible to '[CLPlacemark]'

Error is GetLocationViewController.swift:67:41: '[CLPlacemark]?' is not convertible to '[CLPlacemark]'

推荐答案

看起来您需要先将地标数组拆开(隐式或可选链接),然后再将其分配给[CLPlacemarks]类型

Looks like you need to unwrap the placemarks array (implicitly or optional chaining) before assigning it to a type of [CLPlacemarks]

在您的示例中,您应该使用可选链接,

For your example, you should use optional chaining so

if let validPlacemark = placemarks?[0]{
     let placemark = validPlacemark as? CLPlacemark;
}

不要将所有逻辑放在大括号内,因此,如果找到有效的地标数组,它将执行您所需的命令.如果没有,它将什么也不做,或者您可以随心所欲地处理它

Than place all your logic inside the braces so if it finds a valid placemark array, it will execute your desired commands. If not, it will do nothing or you can handle it however you please

这篇关于"[CLPlacemark]?"不能转换为'[CLPlacemark]'->迅捷2的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-10 14:15