请在下图中找到错误位置:
tripOption中的值数量将在每个请求中更改。
在代码中有一个逻辑问题,例如tripOption只输出2个值..但是循环继续并且表示数组超出索引..我不知道如何解决这个问题。
var arrayOfFlights : [FlightDataModel] = [FlightDataModel]()
if json != nil {
//insert airline data into arrayOfFlights
if let myJSON = json as? [String:AnyObject] {
if let trips = myJSON["trips"] as? [String:AnyObject] {
if let data = trips["data"] as? [String:AnyObject] {
if let carriers = data["carrier"] as? [[String:String]] {
for (index, carrierName) in enumerate(carriers) {
var myFlight = FlightDataModel(airline: carrierName["name"] as String!, price:nil)
self.arrayOfFlights.append(myFlight)
println("\(self.arrayOfFlights[index].airline!)")
}
}
}
if var tripOptions = trips["tripOption"] as? [[String:String]] {
for (index, tripOption) in enumerate(tripOptions) {
self.arrayOfFlights[index].price = tripOption["saleTotal"] as String!
println("price \(self.arrayOfFlights[index].price!)")
}
}
}
}
url jsjon请求中的参数:
var parameters = [
"request": [
"slice": [
[
"origin": from,
"destination": to,
"date": when
]
],
"passengers": [
"adultCount": 1,
"infantInLapCount": 0,
"infantInSeatCount": 0,
"childCount": 0,
"seniorCount": 0
],
"solutions": 5,
"refundable": false
]
]
答案 0 :(得分:0)
该错误是因为您尝试访问arrayOfFlights
中索引大于其size - 1
的元素。
答案 1 :(得分:0)
// index > no of existing elements in the array
self.arrayOfFlights[index].price = tripOption["saleTotal"] as String!
也许您正在尝试将新元素推送到空数组中?
self.arrayOfFlightPrices.append(tripOption["saleTotal"] as String!)
答案 2 :(得分:0)
您应该简化代码并使用结果的第一次迭代来确保您不会超出范围。像这样的东西:
var arrayOfFlights : [FlightDataModel] = [FlightDataModel]()
if let data = json as? NSDictionary {
if let carriers = data.valueForKeyPath("trips.data.carrier") as? NSArray {
for (index, carrier) in enumerate(carriers) {
var myFlight = FlightDataModel(airline: carrier["name"] as String!, price:nil)
arrayOfFlights.append(myFlight)
}
}
if let trips = data.valueForKey("trips") as? NSArray where arrayOfFlights.count > 0 {
for (index, carrier) in enumerate(arrayOfFlights) {
carrier.price = trips.objectAtIndex(index)["saleTotal"] as String!
}
}
}