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

前端之家收集整理的这篇文章主要介绍了ios – Swift无法分配类型[CLLocationCoordinate2D]的不可变值前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
有人可以解释为什么我收到错误“无法分配类型[CLLocationCoordinate2D]的不可变值”我会给出两个场景.我希望第二个工作的原因是因为我将处于循环中并且需要每次都将它传递给drawShape函数.

代码有效:

  1. func drawShape() {
  2. var coordinates = [
  3. 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,]
  4. var shape = MGLPolygon(coordinates: &coordinates,count: UInt(coordinates.count))
  5. mapView.addAnnotation(shape)
  6. }

代码不起作用:

  1. override func viewDidLoad() {
  2. super.viewDidLoad()
  3.  
  4. // does stuff
  5. var coords: [CLLocationCoordinate2D] = [
  6. CLLocationCoordinate2D(latitude: 40.96156150486786,]
  7.  
  8. self.drawShape(coords)
  9. }
  10.  
  11. func drawShape(coords: [CLLocationCoordinate2D]) {
  12. var shape = MGLPolygon(coordinates: &coords,count: UInt(coords.count)) //---this is where the error shows up
  13. mapView.addAnnotation(shape)
  14. }

我不明白为什么这不起作用.我甚至有println(coordinates)和println(coords),它给了我相同的输出.

解决方法

将参数传递给函数时,默认情况下它们将作为不可变传递.就像你将它们声明为let一样.

当您将coords param传递给MGPolygon方法时,它将作为inout参数传递,这意味着这些值可以更改,但由于参数默认为不可变值,因此编译器会抱怨.

您可以通过明确告诉编译器可以通过在其前面加上var来修改此参数来修复它.

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

使用var前缀参数意味着您可以在函数中改变该值.

编辑:Swift 2.2

请改用关键字inout.

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

猜你在找的iOS相关文章