Cannot index value of type [CLPlacemark] with index type int
I want to get the current location. I am working with swift Xcode 7. I have looked through the PLUSIEUR tutorials but they use the same method every time. Here is my code and my error:
Error: cannot index value of type [CLPlacemark] with index type int
import UIKit
import CoreLocation
class ViewController: UIViewController, CLLocationManagerDelegate {
let LocationManager = CLLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.LocationManager.delegate = self
self.LocationManager.desiredAccuracy = kCLLocationAccuracyBest
self.LocationManager.requestWhenInUseAuthorization()
self.LocationManager.startUpdatingLocation()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [AnyObject]) {
CLGeocoder().reverseGeocodeLocation(manager.location!, completionHandler: { (placemarks, error) -> Void in
if (error != nil) {
print("Error")
return
}
if placemarks!.count > 0 {
let pm = placemarks[0] as CLPlacemark
self.displayLocationInfo(pm)
}
else {
print("errorData")
}
})
}
func displayLocationInfo(placemark: CLPlacemark){
self.LocationManager.stopUpdatingLocation()
print(placemark.locality)
print(placemark.postalCode)
print(placemark.administrativeArea)
print(placemark.country)
}
func locationManager(manager: CLLocationManager, didFailWithError error: NSError) {
print("Error:" + error.localizedDescription)
}
}
+3
source to share
3 answers
No, in Xcode 7 the error is:
error: cannot index value of type '[CLPlacemark]?' with an index of type 'Int'
Note ?
. You have to expand this optional. So you can replace:
if placemarks!.count > 0 {
let placemark = placemarks[0] as CLPlacemark
self.displayLocationInfo(placemark)
}
from:
if let placemark = placemarks?.first {
self.displayLocationInfo(placemark)
}
+14
source to share
if placemarks!.count > 0
{
var pm:CLPlacemark!
pm = placemarks![0] as CLPlacemark
//let pm:CLPlacemark = placemarks.
self.displayLocationInfo(pm)
let locality = (pm.locality != nil) ? pm.locality : ""
let sublocality = (pm.subLocality != nil) ? pm.subLocality : ""
let thoroughfare = (pm.thoroughfare != nil) ? pm.thoroughfare : ""
let country = (pm.country != nil) ? pm.country : ""
let administrativeArea = (pm.administrativeArea != nil) ? pm.administrativeArea : ""
print(pm.subLocality)
var annotation = MKPointAnnotation()
annotation.coordinate = coordinate
annotation.title = "\(thoroughfare) \(sublocality), \(locality)"
annotation.subtitle = "\(administrativeArea), \(country)";
self.mapViewForVisitLocation.addAnnotation(annotation)
}
It works for me in X-Code 7 and Swift 2.0.
0
source to share