Bishan
Bishan

Reputation: 401

How to swap NSArray elements in swift

I have an NSArray declared as

var GetVehicleData :NSArray!

And this is the Json data im storing inside the Array,

{
      "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"
    }

Now i want to swap those elements according to distance data im getting from google matrix API. As a example if i want to swap 2nd index element of this array with its 1st index element what should i do?

Ive tried using,

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

but it giving me this error,

Cannot pass immutable value as inout arguments: subscript is get-only

Upvotes: 0

Views: 386

Answers (2)

Ali Beadle
Ali Beadle

Reputation: 4526

(Edit: the following is my original answer to the question and it is still technically accurate, but note that vadian's advice to use Swift arrays is better unless you have a particular need for NSArray/NSMutableArray.)

You cannot edit an NSArray, use an NSMutableArray instead:

var GetVehicleData :NSMutableArray!

Upvotes: 2

vadian
vadian

Reputation: 285290

Use Swift array, as var you get mutability for free:

var GetVehicleData : [[String:Any]]!

Upvotes: 2

Related Questions