在Swift中将对象写入CSV时如何处理逗号? [英] How do I deal with commas when writing Objects to CSV in Swift?
问题描述
似乎还有其他答案,这在堆栈上溢出,但是没有什么是swift特有的.
There seem to be other answers the this on stack overflow but nothing that is specific to swift.
我正在从包含3个属性的站点对象生成CSV
I am generating a CSV from an Site Object containing 3 properties
Struct SiteDetails {
var siteName:String?
var siteType: String?
var siteUrl: String?
}
问题在于siteName可能包含逗号,因此当我读回CSV文件时,由于某些行包含4个或更多CSV元素,因此它真的很难从CSV转换回对象.
The problem is that siteName may contain a comma so its making it really hard to convert back from CSV into a object when I read the CSV file back as some lines have 4 or more CSV elements.
这是我用来导出为CSV的代码:
Here is the code I am using to export to CSV:
func convertToCSV(sites: [SiteDetails]) -> String {
var siteAsCSV = ""
siteAsCSV.appendContentsOf("siteName,siteType,siteUrl\n")
for site in sites {
siteAsCSV.appendContentsOf("\(site.siteName),\(site.siteType),\(site.siteUrl)\n")
}
}
有什么想法可以阻止这个额外的逗号问题吗?
Any ideas how to stop this extra comma issue?
推荐答案
CSV规范建议将所有包含特殊字符的字段都用双引号引起来.
The CSV specification suggests to wrap all fields containing special characters in double quotes.
这篇关于在Swift中将对象写入CSV时如何处理逗号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!