结果类型元素dos与期望类型Swift2不匹配

时间:2015-08-11 15:36:53

标签: xcode swift2

当我尝试运行代码时出现以下错误。在此之前工作我升级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)

        }

    })
}

enter image description here

1 个答案:

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

    }
}