在Swift中将对象写入CSV时如何处理逗号? [英] How do I deal with commas when writing Objects to CSV in Swift?

查看:45
本文介绍了在Swift中将对象写入CSV时如何处理逗号?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

似乎还有其他答案,这在堆栈上溢出,但是没有什么是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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆