如何创建字典从斯威夫特一个txt文件中的数组?(How can I create an array

2019-10-22 02:57发布

这是txt文件的样本。

ROUTE_ID,agency_id,route_short_name,route_long_name,route_desc,route_type,route_url,route_color,route_text_color

53739,11,11TH AVENUE ,, 3,3333CC,FFFFFF

53740,17,1700 SOUTH ,, 3,3333CC,FFFFFF 53741,2200 SOUTH ,, 3,3333CC,FFFFFF

第一行显示的元素的名称和每一个部件由逗号分隔。

我想创建词典,看起来像这样的数组:

[[ “ROUTE_ID”: “53739”, “agency_id”: “”, “route_short_name”: “17” ......]

[ “ROUTE_ID”: “53740”, “agency_id”: “” ......]]

我猜你上心。

Answer 1:

来源: http://pjeremymalouf.com/scan-a-csv-into-swift/

import Foundation

class CSVScanner {

    class func arrayOfDictionaryFromFile(#columnNames:Array<String>, fromFile theFileName:String, withFunction theFunction:(Dictionary<String, String>)->()) {

        if let strBundle = NSBundle.mainBundle().pathForResource(theFileName, ofType: "csv") {

            var encodingError:NSError? = nil

            if let fileObject = NSString(contentsOfFile: strBundle, encoding: NSUTF8StringEncoding, error: &encodingError){

                var fileObjectCleaned = fileObject.stringByReplacingOccurrencesOfString("\r", withString: "\n")

                fileObjectCleaned = fileObjectCleaned.stringByReplacingOccurrencesOfString("\n\n", withString: "\n")

                let objectArray = fileObjectCleaned.componentsSeparatedByString("\n")

                for anObjectRow in objectArray {

                    let objectColumns = anObjectRow.componentsSeparatedByString(",")

                    var aDictionaryEntry = Dictionary<String, String>()

                    var columnIndex = 0

                    for anObjectColumn in objectColumns {

                        aDictionaryEntry[columnNames[columnIndex]] = anObjectColumn.stringByReplacingOccurrencesOfString("\"", withString: "", options: NSStringCompareOptions.CaseInsensitiveSearch, range: nil)

                        columnIndex++
                    }

                    if (aDictionaryEntry.count > 1) {
                        theFunction(aDictionaryEntry)
                    }
                }
            }
        }
    }
}

如何使用它 :

var myCSVContents = Array<Dictionary<String, String>>()

CSVScanner.runFunctionOnRowsFromFile(["title", "body", "category"], withFileName: "fileName.csv", withFunction: {

    (aRow:Dictionary<String, String>) in

    myCSVContents.append(aRow)

})

确保将文件保存为.csv或调整代码查找.TXT



Answer 2:

我建议你做与JSON格式的文本文件,并解析它。 我认为这将是您更简单的方法。



文章来源: How can I create an array of dictionary from a txt file in Swift?