如何在swift中交换NSArray元素

时间:2017-03-25 08:09:40

标签: ios swift swift2 nsarray

我将NSArray声明为

obj.src = "green3.jpg";

这是存储在数组中的Json数据,

var GetVehicleData :NSArray!

现在我想根据来自谷歌矩阵API的距离数据交换这些元素。作为一个例子,如果我想将这个数组的第二个索引元素与第一个索引元素交换,我该怎么办?

我试过用,

{
      "vehicle": "1",
      "plate_no": "1111111111",
      "vehicle_id": 1,
      "pro_pic": "1490258953381.jpg",
      "fname": "Test",
      "lname": "User 01",
      "phone": "+9476112282334",
      "passenger_no": 4,
      "model": "honda",
      "colour": "red",
      "driver_id": "3",
      "lat": "6.8964",
      "lng": "79.8885"
    },
    {
      "vehicle": "2",
      "plate_no": "CAQ-1234",
      "vehicle_id": 2,
      "pro_pic": "1490258754529.jpg",
      "fname": "Test",
      "lname": "User 2",
      "phone": "+9477789424897",
      "passenger_no": 4,
      "model": "Honda",
      "colour": "Black",
      "driver_id": "4",
      "lat": "6.8876886",
      "lng": "79.8628148"
    },
    {
      "vehicle": "3",
      "plate_no": "FGH-1234",
      "vehicle_id": 3,
      "pro_pic": "1490258812119.jpg",
      "fname": "Test ",
      "lname": "User 3",
      "phone": "+9476533142335",
      "passenger_no": 1,
      "model": "TVS",
      "colour": "red",
      "driver_id": "6",
      "lat": "6.8876901",
      "lng": "79.8628141"
    }

但它给了我这个错误,

swap(&GetVehicleData[1], & GetVehicleData[2])

2 个答案:

答案 0 :(得分:2)

(编辑:以下是我对问题的原始答案,它在技术上仍然准确,但请注意,除非您特别需要NSArray / NSMutableArray,否则vadian建议使用Swift数组会更好。)

您无法编辑NSArray,而是使用NSMutableArray:

var GetVehicleData :NSMutableArray!

答案 1 :(得分:2)

使用Swift数组,因为var你可以免费获得可变性:

var GetVehicleData : [[String:Any]]!