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

后端 未结 2 1642
傲寒
傲寒 2021-01-29 06:20

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

相关标签:
2条回答
  • 2021-01-29 07:00

    The CSV specification suggests to wrap all fields containing special characters in double quotes.

    0 讨论(0)
  • 2021-01-29 07:10

    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")
        }
    }
    
    0 讨论(0)
提交回复
热议问题