user1707895
user1707895

Reputation: 13

"downcast from CLplacemark? to Clplacemark only unwraps optional"(swift2)

how to fix this error :

"downcast from CLplacemark? to Clplacemark only unwraps optional"

so i use this code :

if let p = CLPlacemark(placemark: placemarks.first as? CLPlacemark){}

and change placemarks[0] array but not work

and my code is :

CLGeocoder().reverseGeocodeLocation(userLocation) { (placemarks, error) -> Void in

    if error == nil {

       if let p = CLPlacemark(placemark: placemarks[0] as? CLPlacemark){

            print(p)
            self.adsresslabel.text = "\(p.administrativeArea)\(p.postalCode)\(p.country)"
        }


    }else {
        print (error)
    }


    }

at this code :

if let p = CLPlacemark(placemark: placemarks[0] as? CLPlacemark)

i have error about

 "downcast from CLplacemark? to Clplacemark only unwraps optional"

how to fix this error ?!

Upvotes: 0

Views: 290

Answers (2)

vadian
vadian

Reputation: 285260

The completion handler of reverseGeocodeLocation:completionHandler is declared as

typealias CLGeocodeCompletionHandler = ([CLPlacemark]?, NSError?) -> Void

The placemarks are an optional array of CLPlacemark items therefore a down cast is not needed. You have only to check if the array is not nil and not empty as described in the answer of Alain T.

Upvotes: 0

Alain T.
Alain T.

Reputation: 42139

If you don't actually need to make a copy of the first placemark, you only need to do :

if let p = placemarks.first
{
        print(p)
        self.adsresslabel.text = "\(p.administrativeArea)\(p.postalCode)\(p.country)"
}

On the other hand, if you do need it to be a copy:

if let p0 = placemarks.first
{ 
        let p = CLPlacemark(placemark:p0)
        print(p)
        self.adsresslabel.text = "\(p.administrativeArea)\(p.postalCode)\(p.country)"
}

Upvotes: 0

Related Questions