简体   繁体   中英

How can I create an array of dictionary from a txt file in Swift?

This is the sample of the txt file.

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,,2,200 SOUTH,,3,,3333CC,FFFFFF

first line shows the name of the elements and each components are separated by commas.

I want to create an array of dictionaries that looks like this:

[ ["route_id":"53739", "agency_id": "", "route_short_name":"17"......]

["route_id":"53740", "agency_id":""...... ]]

I guess you got the idea.

Source : 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)
                    }
                }
            }
        }
    }
}

How to use it :

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

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

    (aRow:Dictionary<String, String>) in

    myCSVContents.append(aRow)

})

Make sure to save your file as .csv or adapt code to look for .txt

I recommend you to make your text file with JSON format and parse it. I think it will be your easier way.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM