如何交换 swift 中的 NSArray 元素
How to swap NSArray elements in swift
我有一个声明为
的 NSArray
var GetVehicleData :NSArray!
这是 Json 存储在数组中的数据,
{
"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"
}
现在我想根据从 google 矩阵 API 获得的距离数据交换这些元素。例如,如果我想将此数组的第二个索引元素与其第一个索引元素交换,我应该怎么做?
我试过使用,
swap(&GetVehicleData[1], & GetVehicleData[2])
但它给我这个错误,
Cannot pass immutable value as inout arguments: subscript is get-only
(编辑:以下是我对问题的原始回答,从技术上讲它仍然是准确的,但请注意,vadian 建议使用 Swift 数组更好,除非您有特殊需要 NSArray/NSMutableArray.)
您不能编辑 NSArray,请改用 NSMutableArray:
var GetVehicleData :NSMutableArray!
使用 Swift 数组,因为 var
您可以免费获得可变性:
var GetVehicleData : [[String:Any]]!
我有一个声明为
的 NSArrayvar GetVehicleData :NSArray!
这是 Json 存储在数组中的数据,
{
"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"
}
现在我想根据从 google 矩阵 API 获得的距离数据交换这些元素。例如,如果我想将此数组的第二个索引元素与其第一个索引元素交换,我应该怎么做?
我试过使用,
swap(&GetVehicleData[1], & GetVehicleData[2])
但它给我这个错误,
Cannot pass immutable value as inout arguments: subscript is get-only
(编辑:以下是我对问题的原始回答,从技术上讲它仍然是准确的,但请注意,vadian 建议使用 Swift 数组更好,除非您有特殊需要 NSArray/NSMutableArray.)
您不能编辑 NSArray,请改用 NSMutableArray:
var GetVehicleData :NSMutableArray!
使用 Swift 数组,因为 var
您可以免费获得可变性:
var GetVehicleData : [[String:Any]]!