在Swift中parsingCSV文件

当应用程序启动时,我需要将数据预加载到我的tableView中。 所以我通过parsing.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 (eg 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) 

致命错误:数组索引超出范围

我究竟做错了什么 ? 请帮帮我。

您正试图parsing文件path而不是文件的内容

如果你更换

 let content = String(contentsOfURL: contentsOfURL, encoding: encoding, error: error) 

有:

 if let data = NSData(contentsOfURL: contentsOfURL) { if let content = NSString(data: data, encoding: NSUTF8StringEncoding) { //existing code } } 

那么代码将适用于您的示例文件。

根据错误和错误发生的地方,我猜你的values数组没有像你想的那样的5个元素。 我会在给你一个错误的线上放一个断点,并检查你的valuesvariables,看看有多less个断点。 由于你的.csv文件显然是5个元素,所以我想你的parsing中会出现问题。