Reputation: 31
My code is getting information (names , latitudes, longitudes, and cities they are in) from a local .txt file. It works fine up until certain rows, then gives this "Array index out of range error" at certain rows. Below is my code and the txt file:
let path = NSBundle.mainBundle().pathForResource("wifi (1)", ofType: "txt")
let filemgr = NSFileManager.defaultManager()
if filemgr.fileExistsAtPath(path!){
do{
let fullText = try String(contentsOfFile: path!, encoding: NSUTF8StringEncoding)
let readings = fullText.componentsSeparatedByString("\n")
for i in 1..<readings.count{
let data = readings[i].componentsSeparatedByString("\t") as [String]
dictClients["name"] = "\(data[0])"
dictClients["lat"] = "\(data[1])"
dictClients["lng"] = "\(data[2])"
dictClients["city"] = "\(data[3])"
arrayClients.addObject(dictClients)
print(dictClients["name"])
}
}catch let error as NSError{
print(error)
}
}
A sample of the .txt file (where it would cut out on the BBs the Crescent line):
Sky Court Shopping Shannon -8.8818377 52.710461 Clare\ Perys Hotel Limerick -8.6484363 52.6629662 Limerick\ BBs Jetland Shopping Center -8.6966707 52.6734915 Limerick\ Statoil Caherdavin -8.6456267 52.6650273 Limerick\ BBs The Crescent Shopping Centre -8.6480104 52.6405294 Limerick\
Upvotes: 1
Views: 775
Reputation: 726479
It looks like your file has some empty lines - probably, at the end. You need to guard against that.
In addition, dictClients
appears to be a shared object which you add to arrayClients
multiple times. This would create an unexpected behavior after you fix the exception - all entries will match the last entry. You should fix it by creating a new dictionary on each loop iteration:
for str in readings {
let data = s.componentsSeparatedByString("\t") as [String]
// Skip lines that do not contain exactly four tokens
if (data.count != 4) {
continue
}
let dict [String:String] = {
"name" : data[0]
, "lat" : data[1]
, "lng" : data[2]
, "city" : data[3]
}
arrayClients.addObject(dict)
print(dict["name"])
}
Upvotes: 2
Reputation: 5186
Problem is here for i in 1..<readings.count
If the reading array is empty, but your loop always start with index 1 thats why it shows the error. You should start your loop from 0. like
for i in 0..<readings.count
Upvotes: 0