Разбор CSV-файла в SwiftIOS

Программируем под IOS
Ответить
Anonymous
 Разбор CSV-файла в Swift

Сообщение Anonymous »

Мне нужно предварительно загрузить данные в tableView при запуске приложения. Итак, я использую основные данные, анализируя файл .csv. Для этой цели я следую этому руководству.
Вот моя функция parseCSV

Код: Выделить всё

func parseCSV (contentsOfURL: NSURL, encoding: NSStringEncoding, error: NSErrorPointer) -> [(stationName:String, stationType:String, stationLineType: String, stationLatitude: String, stationLongitude: String)]? {
// Load the CSV file and parse it
let delimiter = ","
var stations:[(stationName:String, stationType:String, stationLineType: String, stationLatitude: String, stationLongitude: String)]?

let content = String(contentsOfURL: contentsOfURL, encoding: encoding, error: error)
stations = []
let lines:[String] = content.componentsSeparatedByCharactersInSet(NSCharacterSet.newlineCharacterSet()) as [String]

for line in lines {
var values:[String] = []
if line != "" {
// For a line with double quotes
// we use NSScanner to perform the parsing
if line.rangeOfString("\"") != nil {
var textToScan:String = line
var value:NSString?
var textScanner:NSScanner = NSScanner(string: textToScan)
while textScanner.string != "" {

if (textScanner.string as NSString).substringToIndex(1) == "\"" {
textScanner.scanLocation += 1
textScanner.scanUpToString("\"", intoString: &value)
textScanner.scanLocation += 1
} else {
textScanner.scanUpToString(delimiter, intoString: &value)
}

// Store the value into the values array
values.append(value as! String)

// Retrieve the unscanned remainder of the string
if textScanner.scanLocation < textScanner.string.characters.count {
textToScan = (textScanner.string as NSString).substringFromIndex(textScanner.scanLocation + 1)
} else {
textToScan = ""
}
textScanner = NSScanner(string: textToScan)
}

// For a line without double quotes, we can simply separate the string
// by using the delimiter (e.g. comma)
} else  {
values = line.componentsSeparatedByString(delimiter)
}

// Put the values into the tuple and add it to the items array
let station = (stationName: values[0], stationType: values[1], stationLineType: values[2], stationLatitude: values[3], stationLongitude: values[4])
stations?.append(station)
}
}

return stations
}
это мой образец файла .csv

Код: Выделить всё

Rithala,Underground,Yellow Line,28.7209,77.1070
Но в этой строке появляется ошибка

Код: Выделить всё

let station = (stationName: values[0], stationType: values[1], stationLineType: values[2], stationLatitude: values[3], stationLongitude: values[4])
stations?.append(station)
Неустранимая ошибка: индекс массива выходит за пределы диапазона

Что я делаю неправильно ? Пожалуйста, помогите мне.

Подробнее здесь: https://stackoverflow.com/questions/323 ... e-in-swift
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «IOS»