'[CLPlacemark]? does not convert to '[CLPlacemark]' & # 8594; swift2
this is a piece of code I found on StackOverflow.
It worked in Swift 1.2 Why does this code no longer work 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 error: 67: 41: '[CLPlacemark]?' is not convertible to '[CLPlacemark]'
source to share
It looks like you need to unwrap the labels array (implicitly or optionally chaining) before assigning it to the [CLPlacemarks] type
In your example, you have to use optional chaining so that
if let validPlacemark = placemarks?[0]{
let placemark = validPlacemark as? CLPlacemark;
}
Then put all your logic inside curly braces so that if it finds a valid array of labels, it will execute your desired commands. If not, it won't do anything or you can handle it, but please
source to share
labels are not guaranteed to matter, you can do this:
let placeArray: [CLPlacemark] = placemarks as? [CLPlacemark] ?? []
What reads like
if it placemarks
can be different how [CLPlacemark]
, then do it. Otherwise, assign an empty array.
Here's this code in practice:
Now I understand that you are on Xcode 7! It's even easier, all you need is this:
let placeArray = placemarks ?? []
source to share
In Xcode 7.0 Objective-C has common arrays, so your array is placemarks
no longer [AnyObject]?
as well now [CLLocation]?
. You don't need to allocate the array, you can just expand the additional one. With the addition of guard instructions, your completion block is now as simple as:
geocoder.reverseGeocodeLocation(location) { placemarks, error in
guard let placemarks = placemarks else { print(error); return; }
guard let placemark = placemarks.first else { return; }
// ...
}
source to share