Rufilix Rufilix - 7 months ago 26
Swift Question

create csv file from array of dictionaries in swift

I have an Array of dictionary like this :

The dictionaries are created :

let dateOfSurvey = String(NSDate())
let idOfSurvey = General.codeClasse + "-" + String(General.codePersonnel)
let dictionaryResults = ["dateOfSurvey": dateOfSurvey,
"ID": idOfSurvey,
"themaQuestionStep": questionResultThema,
"actionQuestionStep": questionResultAction,
"F01D1a": questionResult01,
"F02D2c": questionResult02,
"F03D3a": questionResult03,
"F04D4a": questionResult04,
"F05D1b": questionResult05,
"F06D2b": questionResult06,
"F07D3b": questionResult07,
"F08D4b": questionResult08,
"F09D1c": questionResult09,
"F10D2a": questionResult10,
"F11D3c": questionResult11,
"F12D4c": questionResult12]


then added to an array :

arrayOfResults.addObject(dictionaryResults)


I would like to send/export the result by mail and think a CSV file would be a good way.

Is there a simple way to create this csv from the array of dictionaries in swift ?

Answer

After no solution for array of dict I have to change the data in a list of arrays dictionaryResults become arrayOfSurvey

let dateOfSurvey = String(NSDate())
let idOfSurvey = General.codeClasse + "-" + String(General.codePersonnel)
let arrayOfSurvey = [dateOfSurvey , idOfSurvey , questionResultThema , questionResultAction, questionResult01, questionResult02, questionResult03, questionResult04, questionResult05, questionResult06, questionResult07, questionResult08, questionResult09, questionResult10, questionResult11, questionResult12]

I lose the key-value but now be able to put the data in cvs

arrayOfResults.addObject(arrayOfSurvey)
let count = arrayOfResults.count
General.cvs = "dateOfSurvey" + "," + "ID" + "," + "themaQuestionStep" + "," + "actionQuestionStep" + "," + "F01D1a" + "," + "F02D2c" + "," + "F03D3a" + "," + "F04D4a" + "," + "F05D1b" + "," + "F06D2b" + "," + "F07D3b" + "," + "F08D4b" + "," + "F09D1c" + "," + "F10D2a" + "," + "F11D3c" + "," + "F12D4c"
for i in 0...count {
    let arrayAtIndex = arrayOfResults.objectAtIndex(i)
    let stringRepresentation = arrayAtIndex.componentsJoinedByString(",")
    General.cvs += "\n" + stringRepresentation
                }
let fileData = General.cvs.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)