swift 3.1 how to get array or dictionary from CSV

前端 未结 4 1269
孤独总比滥情好
孤独总比滥情好 2020-12-24 01:50

How could I use data in this kind of CSV file? Or how could I print for example row 2 value for \"inside\" column and assign it to a property / entity?

I have this k

4条回答
  •  有刺的猬
    2020-12-24 02:44

    What you want to do is splitting up the string in rows and then into columns (basically a two dimensional array of Strings). Swift already provides the components method for that on String structs.

    func csv(data: String) -> [[String]] {
        var result: [[String]] = []
        let rows = data.components(separatedBy: "\n")
        for row in rows {
            let columns = row.components(separatedBy: ";")
            result.append(columns)
        }
        return result
    }
    

    Then you can access any value via:

    var data = readDataFromCSV(fileName: kCSVFileName, fileType: kCSVFileExtension)
    data = cleanRows(file: data)
    let csvRows = csv(data: data)
    print(csvRows[1][1]) //UXM n. 166/167.
    

提交回复
热议问题