数组 – 将.csv数据导入数组

前端之家收集整理的这篇文章主要介绍了数组 – 将.csv数据导入数组前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我在过去几年使用Objective-C.
现在我正在尝试 Xcode 6 beta 4与迅速.

我想导入一个.csv表单我的webserver到一个数组.我在Objective-C中的旧代码是:

NSString *stringURL = @"https:// [URL] /versionen/versionen.csv";
NSURL  *url = [NSURL URLWithString:stringURL];
NSData *urlData = [NSData dataWithContentsOfURL:url];
if ( urlData )
{
    NSString *csvResponseString = [[NSString alloc] initWithData:urlData   encoding:NSUTF8StringEncoding];
    NSArray         *MZVersionDatenZeilen = [csvResponseString componentsSeparatedByString:@"\n"];
    NSEnumerator    *MZVersionEnumerator = [MZVersionDatenZeilen objectEnumerator];
    NSMutableArray  *MZVersionDatenArray = [NSMutableArray arrayWithCapacity:[MZVersionDatenZeilen count]];
    NSString        *MZVersionZeile;
    while (MZVersionZeile = [MZVersionEnumerator nextObject])
    {
        [MZVersionDatenArray addObject:[MZVersionZeile componentsSeparatedByString:@";"]];
    }
}

我怎么可以在Swift这样做?
有最佳做法 – 推荐吗?

有多个swift库可用:

CSVImporter,它是一个适用于处理大型csv文件的异步解析器.

let path = "path/to/your/CSV/file"
let importer = CSVImporter<[String]>(path: path)
importer.startImportingRecords { $0 }.onFinish { importedRecords in
    for record in importedRecords {
        // record is of type [String] and contains all data in a line
    }
}

SwiftCSV,它是一个用于OSX和iOS的简单CSV解析库.

let csvURL = NSURL(string: "users.csv")!
var error: NSErrorPointer = nil
let csv = CSV(contentsOfURL: csvURL,error: error)

// Rows
let rows = csv.rows
let headers = csv.headers  //=> ["id","name","age"]
let alice = csv.rows[0]    //=> ["id": "1","name": "Alice","age": "18"]
let bob = csv.rows[1]      //=> ["id": "2","name": "Bob","age": "19"]

// Columns
let columns = csv.columns
let names = csv.columns["name"]  //=> ["Alice","Bob","Charlie"]
let ages = csv.columns["age"]    //=> ["18","19","20"]

CSwiftV,它是符合rfc4180规范的csv解析器,但根据作者,它全部在内存中,因此不适合大文件.

let inputString = "Year,Make,Model,Description,Price\r\n1997,Ford,E350,descrition,3000.00\r\n1999,Chevy,Venture,another description,4900.00\r\n"
let csv = CSwiftV(String: inputString)

let headers = csv.headers // ["Year","Make","Model","Description","Price"]
let rows = csv.rows 
// [
//  ["1997","Ford","E350","descrition","3000.00"],//  ["1999","Chevy","Venture","another description","4900.00"]
// ]

猜你在找的Swift相关文章