【问题标题】:MKPolygon using Swift (Missing argument for parameter 'interiorPolygons' in call)使用 Swift 的 MKPolygon(调用中缺少参数“interiorPolygons”的参数)
【发布时间】:2014-09-24 02:32:30
【问题描述】:

开发人员, 我正在尝试在地图视图上实现多边形叠加,如下所示:

private func drawOverlayForObject(object: MyStruct) {
    if let coordinates: [CLLocationCoordinate2D] = object.geometry?.coordinates {
        let polygon = MKPolygon(coordinates: coordinates, count: coordinates.count)
        self.mapView.addOverlay(polygon)
    }
}

出现以下错误:

调用中的参数“interiorPolygons”缺少参数

根据文档: Apple Docu:

可变指针

当函数被声明为采用 UnsafeMutablePointer 参数,它可以接受以下任何一种:

  • nil,作为空指针传递
  • UnsafeMutablePointer 值
  • 一个输入输出表达式,其操作数是 Type 类型的存储左值,作为左值的地址传递
  • 一个 in-out [Type] 值,作为指向数组开头的指针传递,并在调用期间延长生命周期

现在我认为我的方法是正确的,提供一个 [CLLocationCoordinate2D] 数组。有没有人遇到过同样的问题并找到了解决方法?

谢谢 罗尼

【问题讨论】:

    标签: ios7 swift ios8 mkpolygon


    【解决方案1】:

    您遇到的错误是 Swift 的神秘方式,即找不到与您的参数匹配的方法。如果您确实尝试传递 interiorPolygons 参数,您会得到同样令人困惑的结果:

    调用中的额外参数“interiorPolygons”

    不过,您的代码非常接近;你只需要几个小改动。在您引用的文档中,它说您可以通过的一件事是:

    一个 in-out [Type] 值,它作为指向开始的指针传递 数组,并在调用期间延长生命周期

    所以,它正在寻找in-out parameter。这是通过传递带有& 前缀的coordinates 来完成的,如下所示:

    MKPolygon(coordinates: &coordinates, count: coordinates.count)
    

    但是,输入输出参数不能是常量。来自文档:

    您只能将变量作为输入输出参数的参数传递。 您不能将常量或文字值作为参数传递,因为 常量和文字不能修改。

    因此,您需要先用var 定义coordinates:

    if var coordinates: [CLLocationCoordinate2D] = object.geometry?.coordinates
    

    这使得整个函数看起来像这样:

    private func drawOverlayForObject(object: MyStruct) {
        if var coordinates: [CLLocationCoordinate2D] = object.geometry?.coordinates {
            let polygon = MKPolygon(coordinates: &coordinates, count: coordinates.count)
            self.mapView.addOverlay(polygon)
        }
    }
    

    【讨论】:

    • 不幸的是,至少在 Swift 2.1 中,这段代码会产生:'&' 与 'UnsafeMutablePointer' 类型的非 inout 参数一起使用
    • @FabrizioBartolomucci 如果coordinates 是用let 而不是var 定义的,您将收到该错误。由于let 使coordinates 不可变,它不能用作inout 参数(在这种情况下,Swift 2.1 仍然有一个半隐秘的错误)。
    【解决方案2】:

    我从几个教程中挑选并整合的最终解决方案:

    func setPolylineFromPoints(locations:[CLLocation]){
        if locations.count == 0 {
            return;
        }
    // while we create the route points, we will also be calculating the bounding box of our route
    // so we can easily zoom in on it.
        var pt : UnsafeMutablePointer<MKMapPoint>? // Optional
        pt = UnsafeMutablePointer.alloc(locations.count)
        for idx in 0..<locations.count-1 {
           let location = locations[idx]
           let point = MKMapPointForCoordinate(location.coordinate);
           pt![idx] = point;
        }
        self.polyline = MKPolyline(points:pt!, count:locations.count-1)
    // clear the memory allocated earlier for the points
        pt?.destroy()
        pt?.dealloc(locations.count)
    }  
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-10-13
      • 2015-03-16
      • 2015-01-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多