【问题标题】:Argument type '[MGLPointAnnotation]' does not conform to expected type 'MGLAnnotation'参数类型“[MGLPointAnnotation]”不符合预期类型“MGLAnnotation”
【发布时间】:2016-09-29 15:15:32
【问题描述】:

我最近开始学习 swift,现在已经迈出了制作自己地图的下一步。我已经成功地用 mapkit 制作了一个应用程序,现在我正在用 mapbox 试试运气,因为我喜欢它的设计功能。

我已经构建了一个字典,其中包含我的位置数据,然后我制作了一个循环,它将数据添加到我的地图中。但是我现在卡住了,因为我收到以下错误:

" 参数类型 '[MGLPointAnnotation]' 不符合预期的类型 'MGLAnnotation'

当我尝试使用我的字典 mapView.addAnnotation 时会发生这种情况。到目前为止,我了解到它与解包字典中的值有关,但是当我通过编写 mapView.addAnnotation(annotations as!MGLAnnotation) 强制解包时,我的应用程序崩溃了。

有人可以告诉我正确的方向吗?我不是在寻找修补程序,而是更多地找出我哪里出错了。非常感谢!

代码如下:

let locations = [
        ["name" : "Apple Inc.",
         "latitude" : 37.33187,
         "longitude" : -122.02951,
         "mediaURL" : "http://www.apple.com"],
        ["name" : "BJ's Restaurant & Brewhouse",
         "latitude" : 37.33131,
         "longitude" : -122.03175,
         "mediaURL" : "http://www.bjsrestaurants.com"]
    ]

    var annotations = [MGLPointAnnotation]()

    for dictionary in locations {
        let latitude = CLLocationDegrees(dictionary["latitude"] as! Double)
        let longitude = CLLocationDegrees(dictionary["longitude"] as! Double)
        let coordinate = CLLocationCoordinate2D(latitude: latitude, longitude: longitude)
        let name = dictionary["name"] as! String
        let discription = dictionary["mediaURL"] as! String
        let annotation = MGLPointAnnotation()
        annotation.coordinate = coordinate
        annotation.title = "\(name)"
        annotation.subtitle = "\(discription)"
        annotations.append(annotation)
    }

mapView.addAnnotation(annotations as! MGLAnnotation)

【问题讨论】:

  • 我仍然遇到这个问题。如果有人有解决方案,或者只是一个可以找到更多信息的大致方向,我将不胜感激!

标签: dictionary annotations mapbox unwrap


【解决方案1】:

您正试图将某事物的数组转换为另一个对象的单个对象...annotations 是一个数组,而 MGLAnnotation 是单个对象。

所以改变 mapView.addAnnotation(annotations as! MGLAnnotation) 到 mapView.addAnnotation(annotations as! [MGLAnnotation])

这应该消除您的错误...但是您也在使用方法addAnnotation,它只需要一个对象作为参数。所以试试: mapView.addAnnotation(annotations[0])

注意:我的第一个解决方案只是演示错误的解决方案 - 由于“只需要一个对象”的情况,它仍然无法工作。

希望这有助于并解释一些事情:)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-05-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多