我有一个小问题,不知道如何解决。 我有三个(或更多)数组,想要创建一个具有通用功能的CSV字符串。
例如:
var firstname = ["Phil", "Kate", "Wendy", "Nick"]
var street = ["Groove Street", "Howard Street", "Highway 98", "Wall Street"]
var country = ["United Kingdom", "Australia", "Canada", "New Zealand"]
我的目标是创建这种类型的函数:
func csvCreator([“firstname“,“street“,“country“]) -> String {}
//the integration of the array is wrong
输出应为:
csvString = “firstname;street;country\nPhil;Groove Street;United Kingdom\nKate;Howard Street;Australia\nWendy;Highway 98;Canada\nNick;Wall Street;New Zealand
我想保持代码的灵活性,以便可以通过编写如下函数简单地添加另一个类别(例如年龄数组):
var age = ["22", "21", "44", "16"]
func csvCreator([“firstname“,“street“,“country“,“age“]) -> String {}
//the integration of the array is wrong
应在函数中使用数组询问变量的名称。
答案 0 :(得分:0)
您需要传递数据数组和列标题数组。
这是一个非常艰难的开始。需要添加和修复许多细节,但这为您提供了一个良好的开端。创建CSV并不像大多数人想象的那么简单。
func csvCreator(titles: [String], data: [[String]]) -> String {
// Add checks to ensure all arrays have the same length
func buildRow(_ values: [String]) -> String {
// This needs lots of work to deal with values that contain ; or newline characters
return values.joined(separator: ";") + "\n"
}
var result = buildRow(titles)
for row in data {
result += buildRow(row)
}
return result
}
那么您可能会这样称呼它:
var firstname = ["Phil", "Kate", "Wendy", "Nick"]
var street = ["Groove Street", "Howard Street", "Highway 98", "Wall Street"]
var country = ["United Kingdom", "Australia", "Canada", "New Zealand"]
let csv = csvCreator(titles: ["firstname","street","country"], data: [firstname, street, country])