How do I deal with commas when writing Objects to CSV in Swift?

对着背影说爱祢 提交于 2021-02-05 12:32:04

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!