当我尝试运行代码时出现以下错误。在此之前工作我升级Xcode并获得IOS9的Xcode Beta版本7.0。要我转换代码到swift 2语法现在它给我错误。我的代码片段如下。
import UIKit
import MapKit
class MapViewController: UIViewController, MKMapViewDelegate {
@IBOutlet var mapView:MKMapView!
var restaurant:Restaurant!
override func viewDidLoad() {
super.viewDidLoad()
mapView.delegate = self
// Convert address to coordinate and annotate it on map
let geoCoder = CLGeocoder()
geoCoder.geocodeAddressString(restaurant.location, completionHandler: { placemarks, error in
if error != nil {
print(error)
return
}
if placemarks != nil && placemarks!.count > 0 {
let placemark = placemarks[0] as! CLPlacemark
// Add Annotation
let annotation = MKPointAnnotation()
annotation.title = self.restaurant.name
annotation.subtitle = self.restaurant.type
annotation.coordinate = placemark.location.coordinate
self.mapView.showAnnotations([annotation], animated: true)
self.mapView.selectAnnotation(annotation, animated: true)
}
})
}
答案 0 :(得分:2)
在Xcode 7.0中,placemarks数组不再是[AnyObject]?但现在是[CLLocation]?没有必要强制转换数组。将保护声明添加到您的快速代码中:
import UIKit
import MapKit
class MapViewController: UIViewController, MKMapViewDelegate {
@IBOutlet var mapView:MKMapView!
var restaurant:Restaurant!
override func viewDidLoad() {
super.viewDidLoad()
mapView.delegate = self
// Convert address to coordinate and annotate it on map
let geoCoder = CLGeocoder()
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation])
{
let location = locations.last
geoCoder.reverseGeocodeLocation(manager.location!) { placemarks, error in
guard let placemarks = placemarks else { print(error); return; }
guard let placemark = placemarks.first else { return; }
let annotation = MKPointAnnotation()
annotation.title = self.restaurant.name
annotation.subtitle = self.restaurant.type
annotation.coordinate = placemark.location!.coordinate
self.mapView.showAnnotations([annotation], animated: true)
self.mapView.selectAnnotation(annotation, animated: true)
}
}
}