不能使用索引typesint来下标types为的值

我想检索当前位置。 我在Swift Xcode 7上工作。我看了PLUSIEUR教程,但每次使用相同的方法。 这是我的代码和我的错误:!

错误:不能使用索引typesint来下标types为[CLPlacemark]的值

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) } } 

不,在Xcode 7中的错误是:

错误:不能下标'[CLPlacemark]?'的值 用'Int'types的索引

注意到? 。 你必须打开那个可选的。 所以你可以replace:

 if placemarks!.count > 0 { let placemark = placemarks[0] as CLPlacemark self.displayLocationInfo(placemark) } 

有:

 if let placemark = placemarks?.first { self.displayLocationInfo(placemark) } 

我也遇到了几乎相同的情况。 同样的提示是,它认为它不是解包所以把一个! 进入它为我工作。

尝试这个。

 let pm = placemarks![0] as CLPlacemark 
  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) } 

它适用于X-Code 7和Swift 2.0。