swift 3.1如何从CSV获取数组或字典

前端之家收集整理的这篇文章主要介绍了swift 3.1如何从CSV获取数组或字典前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我怎样才能在这种CSV文件中使用数据?或者我如何打印“内部”列的第2行值并将其分配给属性/实体?

我有这种从excel文件转换为Numbers的文件,我想抓取每列的数据并使用它们.

原始CSV文件以数字打开:

我得到的控制台输出

使用这种方法

func readDataFromCSV(fileName:String,fileType: String)-> String!{
        guard let filepath = Bundle.main.path(forResource: fileName,ofType: fileType)
            else {
                return nil
        }
        do {
            var contents = try String(contentsOfFile: filepath,encoding: .utf8)
            contents = cleanRows(file: contents)
            return contents
        } catch {
            print("File Read Error for file \(filepath)")
            return nil
        }
    }


func cleanRows(file:String)->String{
    var cleanFile = file
    cleanFile = cleanFile.replacingOccurrences(of: "\r",with: "\n")
    cleanFile = cleanFile.replacingOccurrences(of: "\n\n",with: "\n")
    //        cleanFile = cleanFile.replacingOccurrences(of: ";;",with: "")
    //        cleanFile = cleanFile.replacingOccurrences(of: ";\n",with: "")
    return cleanFile
}

解决方案感谢Jens Meder

运用

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
    }

在viewDidLoad中

var data = readDataFromCSV(fileName: kCSVFileName,fileType: kCSVFileExtension)
    data = cleanRows(file: data!)
    let csvRows = csv(data: data!)
    print(csvRows[1][1]) // UXM n. 166/167
你想要做的是将字符串分成行然后分成列(基本上是字符串的二维数组). Swift已经为String结构提供了 components方法.
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
}

然后您可以通过以下方式访问任何值

var data = readDataFromCSV(fileName: kCSVFileName,fileType: kCSVFileExtension)
data = cleanRows(file: data)
let csvRows = csv(data: data)
print(csvRows[1][1]) //UXM n. 166/167.
原文链接:https://www.f2er.com/swift/320185.html

猜你在找的Swift相关文章