我是 Swift 新手。我可以从 csv 文件格式读取数据(许多行和列的姓名和邮寄地址)。我有几个这样的文件,因此我创建了一个函数来读取文件并将数据提取到多维数组中 - 名称、地址、城市、州、国家/地区。我从文件中读取每一行并尝试将其附加到多维数组,但出现错误 - 索引超出范围或文件类型不匹配。启用此功能的最佳方法是什么。请参阅下面的代码。
func getMailing(fileName: String) -> ([[String]])? {
let totalList = 243
var tempList: [String] = []
var arrayList = [[String]]()
guard let path = Bundle.main.url(forResource: fileName, withExtension: "csv") else {
print("File Error")
arrayList = [[""]]
return (arrayList)
}
do {
// get mailing data from file
let content = try String(contentsOf:path, encoding: String.Encoding.utf8)
// separate each line entry
tempList = content.components(separatedBy: "\r\n")
for index in 0...totalList - 1 {
// get each line from list and post into an array
let singleLine = tempList[index].components(separatedBy: ",").dropFirst().prefix(5)
// store each line data into into a multidimensional array for easy retrieval
arrayList[index].append(singleLine)
}
}
return (arrayList)
} catch {
print("File Error")
arrayList = [[""]]
return (arrayList)
}
}
最佳答案
根据您显示的代码,您似乎正在尝试更改两个不同空数组的值 243 次。您有一个循环设置可以根据您的 totalList
属性进行迭代,但是我不知道您从哪里获得该值。如果可以的话,以编程方式确定该值是明智的。
您将 tempList
和 arrayList
设置为空数组:
var tempList: [String] = []
var arrayList = [[String]]()
但是随后您将经历一个循环并尝试更改甚至不存在的条目的值,因此您的索引超出范围错误。您需要首先向这两个数组添加一些内容,因为现在它们是空的。当您尝试将 singleLine
设置为 tempList[index].components(separatedBy: ",").dropFirst().prefix(5)
时,第一次循环可能会崩溃code>,因为您说的是 tempList[0].components(separatedBy: ",").dropFirst().prefix(5)
,而没有 tempList 的条目
位于索引 0
处,因为它仍然是空的!如果要循环遍历数组,明智的做法是根据数组的计数来执行此操作,或者至少在需要使用两个不同数组中的索引时进行快速修复:
// Get the maximum times you can iterate based on the lowest count from each array
let maxLoop = min(tempList.count - 1, arrayList.count - 1)
for index in 0...maxLoop {
// get each line from list and post into an array
let singleLine = tempList[index].components(separatedBy: ",").dropFirst().prefix(5)
// store each line data into into a multidimensional array for easy retrieval
arrayList[index].append(singleLine)
}
现在上面的一小块代码甚至不会执行一次循环,因为两个数组仍然是空的。您需要在某个地方获取邮件数据并解析它,以便可以填充 tempList
和 arrayList
关于arrays - 在 Swift 中从 csv 文件读取数据并将数据转换为多维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42127088/