0
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.

SwiftUIを触ってみた Part2

Posted at

今日はCSVの読み込みについてやってみたので備忘録を残しておく

CSVファイルの中のデータを二次元配列に入れる
次のように47都道府県のコンマ区切りのデータを用意して、
前回作ったプロジェクトのContentViewと同じ階層に入れた

SampleCSV.csv
都道府県,
北海道,
青森県,
岩手県,
...

CSVの読み込み

ContentView.swift
struct ContentView: View {
    @State var prefArray: [[String]] = []
    var body: some View {
        VStack {
            RoundedRectangle(cornerRadius: 35)
                .overlay(
                    Text("NEXT")
                        .foregroundColor(.white)
                        .frame(height: 100)
                )
                .foregroundColor(Color(red: 0.226, green: 0.646, blue: 0.953))
                .frame(width: 100, height: 50)
                .onTapGesture {
                    prefArray = loadCSV(fileName: "SampleCSV")
                    print("ラベル: \(prefArray[0][0])")
                    print("1番目の要素: \(prefArray[1][0])")
                    print("3番目の要素: \(prefArray[3][0])")
                }
        }
    }
    // csvを読み込む関数
    func loadCSV(fileName: String) -> [[String]] {
        var csvArray: [[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")
            var lineArray: [String] = lineChange.components(separatedBy: "\n")
            lineArray.removeLast()
            
            for line in lineArray {
                var dataArray: [String] = line.components(separatedBy: ",")
                dataArray.removeLast()
                csvArray.append(dataArray)
            }
        } catch {
            print("Cannot Load \"\(fileName)\"!")
        }
        return csvArray
    }
}

出力結果

ラベル: 都道府県
1番目の要素: 北海道
3番目の要素: 岩手県
0
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
0
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?