Swift 无法分配 [CLLocationCoordinate2D] 类型的不可变值

Swift cannot assign immutable value of type [CLLocationCoordinate2D]

有人可以解释为什么我收到错误 "cannot assign immutable value of type [CLLocationCoordinate2D]" 我将给出两种情况。我希望第二个工作的原因是因为我会处于循环中并且每次都需要将其传递给 drawShape 函数。

此代码有效:

func drawShape() {
    var coordinates = [
        CLLocationCoordinate2D(latitude: 40.96156150486786, longitude: -100.24319656647276),
        CLLocationCoordinate2D(latitude: 40.96456685906742, longitude: -100.25021235388704),
        CLLocationCoordinate2D(latitude: 40.96528813790064, longitude: -100.25022315443493),
        CLLocationCoordinate2D(latitude: 40.96570116316434, longitude: -100.24954721762333),
        CLLocationCoordinate2D(latitude: 40.96553915028926, longitude: -100.24721925915219),
        CLLocationCoordinate2D(latitude: 40.96540144388564, longitude: -100.24319644831121),
        CLLocationCoordinate2D(latitude: 40.96156150486786, longitude: -100.24319656647276),
    ]
    var shape = MGLPolygon(coordinates: &coordinates, count: UInt(coordinates.count))
    mapView.addAnnotation(shape)
}

此代码无效:

override func viewDidLoad() {
    super.viewDidLoad()

    // does stuff
    var coords: [CLLocationCoordinate2D] = [
            CLLocationCoordinate2D(latitude: 40.96156150486786, longitude: -100.24319656647276),
            CLLocationCoordinate2D(latitude: 40.96456685906742, longitude: -100.25021235388704),
            CLLocationCoordinate2D(latitude: 40.96528813790064, longitude: -100.25022315443493),
            CLLocationCoordinate2D(latitude: 40.96570116316434, longitude: -100.24954721762333),
            CLLocationCoordinate2D(latitude: 40.96553915028926, longitude: -100.24721925915219),
            CLLocationCoordinate2D(latitude: 40.96540144388564, longitude: -100.24319644831121),
            CLLocationCoordinate2D(latitude: 40.96156150486786, longitude: -100.24319656647276),
        ]

    self.drawShape(coords)
}

func drawShape(coords: [CLLocationCoordinate2D]) {
    var shape = MGLPolygon(coordinates: &coords, count: UInt(coords.count)) //---this is where the error shows up
    mapView.addAnnotation(shape)
}

我不明白为什么这不起作用。我什至有 println(coordinates)println(coords),它为我提供了相同的输出。

将参数传递给函数时,默认情况下它们是不可变的。就像您将它们声明为 let.

一样

当您将 coords 参数传递给 MGPolygon 方法时,它作为 inout 参数传递,这意味着这些值可以更改,但因为参数是不可变值默认情况下,编译器会报错。

您可以通过明确告诉编译器可以通过在其前面加上 var.

来修改此参数来修复它。
func drawShape(var coords: [CLLocationCoordinate2D]) {
    var shape = MGLPolygon(coordinates: &coords, count: UInt(coords.count)) 
    mapView.addAnnotation(shape)
}

在参数前加上 var 意味着您可以在函数内改变该值。

编辑:Swift 2.2

改用关键字 inout

func drawShape(inout coords: [CLLocationCoordinate2D]) {
    var shape = MGLPolygon(coordinates: &coords, count: UInt(coords.count)) 
    mapView.addAnnotation(shape)
}