问题
There seem to be other answers the this on stack overflow but nothing that is specific to swift.
I am generating a CSV from an Site Object containing 3 properties
Struct SiteDetails {
var siteName:String?
var siteType: String?
var siteUrl: String?
}
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.
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?
回答1:
The CSV specification suggests to wrap all fields containing special characters in double quotes.
回答2:
I managed to get this working using the modification of adding the double quotes to each field. In Swift, this requires you to escape the quotation mark which looks like its not going to run when you look at Xcode's syntax highlighting, but it works fine.
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")
}
}
来源:https://stackoverflow.com/questions/38163508/how-do-i-deal-with-commas-when-writing-objects-to-csv-in-swift