2
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 1 year has passed since last update.

[Swift] csvファイルの読み込み

2
Last updated at Posted at 2021-04-04
    func loadCSV(fileName:String) -> [String] {
        let csvBundle = Bundle.main.path(forResource: fileName, ofType:"csv")!
        do{
            let csvData = try String(contentsOfFile: csvBundle,encoding:String.Encoding.utf8 )
            let lineChange = csvData.replacingOccurrences(of: "\r", with: "\n")
            csvArray = lineChange.components(separatedBy: "\n")
            csvArray.removeLast()
        }catch{
            print("エラー")
        }
        return csvArray
        
    }

loadCSV関数は引数で受け取ったfileNameを元にcsv内も文字列を改行を一つの単位として配列に納めて返す。

let csvBundle = Bundle.main.path(forResource: fileName, ofType:"csv")!
ファイルネームを元にcsvファイルを読み込む。
csvBundleには対象ファイルのフルパスが格納されている。

let csvData = try String(contentsOfFile:csvBundle,encoding:String.Encoding.utf8 )
対象ファイルの中身を取得する。
csvDataにはファイルの記述内容が入る。

let lineChange = csvData.replacingOccurrences(of: "\r", with: "\n")
改行に\rが使われていれば\nに書き換える。

csvArray = lineChange.components(separatedBy: "\n")
\nの改行コードを区切りに配列にぶちこむ

csvArray.removeLast()
リストの一番最後の配列を削除CSVファイルの構造上配列が無駄に作られてしまう

ex)
1 あいうえお\n
2 かきくけこ\n
3 さしすせそ\n
4 たちつてと\n
5 なにぬねの\n
6\n

2
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
2
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?