3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

SwiftでCSV形式の文字列を生成する(Swift2.2)

Last updated at Posted at 2016-04-25

SwiftでCSV形式の文字列を作成するためのメモ。
カンマが入ったデータにも対応させる。

編集前Ver・・・

var csvData = [
    ["1,234", "222", "hoge", "aaa,bbb,ccc", "1,000,000"],
    [1_000_000, 2, 3, 4, 5.555],
]
var s = ""
for a in csvData {
    for aa in a {
        s += "\"\(aa)\","
    }

    s = s.substringToIndex(s.startIndex.advancedBy(s.characters.count - 1))
    s += "\n"
}
s = s.substringToIndex(s.startIndex.advancedBy(s.characters.count - 1))
print(s)

編集後シンプルVer

var csvData = [
    ["1,234", "222", "hoge", "aaa,bbb,ccc", "1,000,000"],
    [1_000_000, 2, 3, 4, 5.555],
]
var s = csvData.map { $0.map { "\"\($0)\"" }.joinWithSeparator(",") }.joinWithSeparator("\n")
print(s)

結果

"1,234","222","hoge","aaa,bbb,ccc","1,000,000"
"1000000","2","3","4","5.555"
3
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?