しめ鯖日記

swift, iPhoneアプリ開発, ruby on rails等のTipsや入門記事書いてます

SwiftでCSVを読み取れるライブラリ - SwiftCSV - を使ってみた

今日はこちらのライブラリを試してみました。

github.com

インストール

インストールはいつものようにCocoaPodsで行います。
CocoaPodsに上がっているものではうまく動かなかったので直接リポジトリを指定してインストールしました。

pod "SwiftCSV", git: 'git@github.com:naoty/SwiftCSV.git'

使い方

サンプルとして下のようなCSVを作成しました。

id,name,description
1,名前1,説明1
2,名前2,説明2
3,名前3,説明3

READMEを見ながら動かしてみました。
シンプルで使いやすそうです。

import SwiftCSV

let fileLocation = NSBundle.mainBundle().pathForResource("Sample", ofType: "csv")!
let error: NSErrorPointer = nil

if let csv = CSV(contentsOfFile: fileLocation, error: error) {
    print(csv.headers) // ["id", "name", "description"]
    print(csv.columns) // ["id": ["1", "2", "3"], "description": ["説明1", "説明2", "説明3"], "name": ["名前1", "名前2", "名前3"]]
    print(csv.rows) // [["id": "1", "description": "説明1", "name": "名前1"], ["id": "2", "description": "説明2", "name": "名前2"], ["id": "3", "description": "説明3", "name": "名前3"]]
}