-1

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?

x4h1d
  • 6,042
  • 1
  • 31
  • 46
UKDataGeek
  • 6,338
  • 9
  • 46
  • 63
  • @Martin R Can you remove the duplicate as the answer you shared doesn't have a swift specific answer – UKDataGeek Jul 03 '16 at 08:39
  • I have reopened the question. However, the answer to *"How do I deal with commas when writing Objects to CSV"* is *"enclose each field in double quotes"*, as described in http://stackoverflow.com/questions/769621/dealing-with-commas-in-a-csv-file, no matter which language you use. If you don't know how to print quotation marks before and after each field in Swift then I would suggest that you update the question accordingly. – Martin R Jul 03 '16 at 09:02

2 Answers2

7

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

Community
  • 1
  • 1
vadian
  • 274,689
  • 30
  • 353
  • 361
  • How do you do this in swift ? – UKDataGeek Jul 03 '16 at 08:37
  • Sorry, your code is too inconsistent, for example the naming (`sitename` vs. `SiteName`) and type mismatch of the parameter (`sites` is supposed to be an array but `site` – another naming confusion because of the lowercase letter –  is not). Apart from that it's a remarkable negative example of abusing optionals since all fields in CSV are required, so they could never be `nil`. – vadian Jul 03 '16 at 10:28
  • thanks - I tidied it up. I wrote it quite late as simple case to demonstrate – UKDataGeek Jul 03 '16 at 12:47
3

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")
    }
}
x4h1d
  • 6,042
  • 1
  • 31
  • 46
UKDataGeek
  • 6,338
  • 9
  • 46
  • 63