Firestoreに記録しているInt型のフィールドを取得・CollectionViewのセル内ラベルに表示したい
お世話になります。
現在、食材検索・食事記録サービスを開発しながらSwiftとFirebaseを学んでいる初学者です。
以前下記リンクのような質問をさせていただきました。
https://teratail.com/questions/199897
この質問にいただいた回答を基に、Firestore内に入れているInt型のデータをラベルに表示するコードを以下のように書いたのですが、実行するとアプリが落ちてしまいます。
なお、Firestoreには
- 食品名(String)
- メーカー名(String)
- 価格(Number)
というデータが2つ入っております。
String型のデータは正しく表示されていることもあり、どうしてInt型だと配列に追加・ラベルに上手く表示できないのか分かりません。
どなたか解決策をご存知の方がいらっしゃいましたら、教えていただきたいです。
該当のソースコード
Swift
1// ViewController 2var foodNameArray: [String] = [] 3var priceArray: [Int] = [] 4class ViewController: UIViewController, UICollectionViewDataSource, UISearchBarDelegate { 5 //中略 6 7 // セルを表示する内容 8 func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { 9 10 let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! CollectionViewCell2 11 cell.label1.text = foodNameArray[indexPath.row] 12 // 表示されないラベルは以下 13 cell.label2.text = String(priceArray[indexPath.row]) 14 cell.btn1.tag = indexPath.row 15 cell.setCell() 16 return cell 17 } 18 19 // Firestoreからデータをもってくる 20 private func loadData() { 21 22 let db = Firestore.firestore() 23 db.collection("items").getDocuments() { (querySnapshot, err) in 24 if let err = err { 25 print("Error getting documents: (err)") 26 } 27 for document in querySnapshot!.documents { 28 if let foodName = document.data()["name"] as? String{ 29 foodNameArray.append(foodName) 30 } 31 if let priceDetail = document.data()["price"] as? Int{ 32 priceArray.append(priceDetail) 33 } 34 } 35 self.collectionViewObj.reloadData() 36 } 37 }
質問内容に不備・不明瞭な点がありましたら、ご指摘いただけますと助かります。
よろしくお願いいたします。
補足情報(FW/ツールのバージョンなど)
Swift version 5.0.1
Xcode version 10.2.1
回答1件
あなたの回答
tips
プレビュー