質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.49%
Firebase

Firebaseは、Googleが提供するBasSサービスの一つ。リアルタイム通知可能、並びにアクセス制御ができるオブジェクトデータベース機能を備えます。さらに認証機能、アプリケーションのログ解析機能などの利用も可能です。

Swift Playground

Swift Playgroundは、Swiftをインタラクティブに習得できるiPad向けのアプリケーション。コーディングの知識は一切必要なく、Swift Playgrounds上でプログラミングしたコードによりドローン・ロボットを自在に動かすことが可能です。

Swift

Swiftは、アップルのiOSおよびOS Xのためのプログラミング言語で、Objective-CやObjective-C++と共存することが意図されています

Q&A

0回答

880閲覧

Swift5 Thread 1: Fatal error: Index out of rangeの解決方法を教えてください。

gaa

総合スコア0

Firebase

Firebaseは、Googleが提供するBasSサービスの一つ。リアルタイム通知可能、並びにアクセス制御ができるオブジェクトデータベース機能を備えます。さらに認証機能、アプリケーションのログ解析機能などの利用も可能です。

Swift Playground

Swift Playgroundは、Swiftをインタラクティブに習得できるiPad向けのアプリケーション。コーディングの知識は一切必要なく、Swift Playgrounds上でプログラミングしたコードによりドローン・ロボットを自在に動かすことが可能です。

Swift

Swiftは、アップルのiOSおよびOS Xのためのプログラミング言語で、Objective-CやObjective-C++と共存することが意図されています

0グッド

0クリップ

投稿2021/09/13 17:23

前提・実現したいこと

Swiftでアプリを作っていて、UIUISearchBar検索機能を実装しようとしていました。しかしsearchDataList[index.row]にThread 1: Fatal error: Index out of rangeというエラーが発生しました。何が原因でこのようなエラーが発生しているか分からないので返信してくれるととても助かります!!
何卒よろしく御願い致します!!

発生している問題・エラーメッセージ

Thread 1: Fatal error: Index out of range

該当のソースコード

Swift

1 2 3class MedicineData{ 4 5 let hospitalData:String? 6 let examinationData:String? 7 let photoData:String? 8 let docId:String? 9 let userName:String? 10 let time:String? 11 init(doc: DocumentSnapshot) { 12 13 let Doc = doc.data() 14 self.userName = Doc!["name"] as? String 15 self.docId = doc.documentID 16 self.examinationData = Doc!["examinationData"] as? String 17 self.hospitalData = Doc!["hospitalData"] as? String 18 self.time = Doc!["time"] as? String 19 self.photoData = Doc!["photoData"] as? String 20 } 21} 22 23 24class MedicineViewController: UIViewController,UITableViewDelegate,UITableViewDataSource, UISearchBarDelegate,MedicineViewDelegate { 25 26 func photoButtonTaped() { 27 let PhotoViewController = self.storyboard?.instantiateViewController(withIdentifier: "PhotoViewController") as! MedicineViewController 28 self.navigationController?.pushViewController( PhotoViewController, animated: true) 29 } 30 31 32 33 34 var medicineDataList:[MedicineData] = [] 35 36 var searchDataList:[MedicineData] = [] 37 38 var longPressRecognizer = UILongPressGestureRecognizer(target: self, action: "CustomTableViewCell") 39 40 41 42 let image = UIImage(named: "no image icon") 43 44 let photo = UIImage(named: "(String(describing: medicalList.photoData))") 45 46 @IBOutlet weak var medicineSearchBar: UISearchBar! 47 48 @IBOutlet weak var tableView: UITableView! 49 50 51 52 @IBOutlet weak var AddPageButton: UIButton! 53 54 let userID = Auth.auth().currentUser?.uid 55 56 var startingFrame : CGRect! 57 var endingFrame : CGRect! 58 59 60 func scrollViewDidScroll(_ scrollView: UIScrollView) { 61 62 if (scrollView.contentOffset.y >= (scrollView.contentSize.height - scrollView.frame.size.height)) && self.AddPageButton.isHidden { 63 64 self.AddPageButton.isHidden = false 65 66 self.AddPageButton.frame = startingFrame 67 68 UIView.animate(withDuration: 1.0) { 69 70 self.AddPageButton.frame = self.endingFrame 71 } 72 } 73 } 74 75 func configureSizes() { 76 let screenSize = UIScreen.main.bounds 77 let screenWidth = screenSize.width 78 let screenHeight = screenSize.height 79 startingFrame = CGRect(x: 0, y: screenHeight+100, width: screenWidth, height: 100) 80 endingFrame = CGRect(x: 0, y: screenHeight-100, width: screenWidth, height: 100) 81 82 } 83 84 85 private func getData(){ 86 //Firebaseのデータを取得してそれを配列にする 87 let Ref = Firestore.firestore().collection("users").document(userID!).collection("medicinedata") 88 89 Ref.getDocuments(){(data, error) 90 in if let error = error{ 91 print(error) 92 return 93 } 94 //querySnapshotにドキュメントデータが配列になって入っている。 95 96 self.medicineDataList = data!.documents.map { document in 97 let setdata = MedicineData(doc: document) 98 print(self.medicineDataList) 99 return setdata 100 } 101 //tableViewを更新 102 self.tableView.reloadData() 103 } 104 } 105 106 107 108 109 override func viewDidLoad() { 110 super.viewDidLoad() 111 getData() 112 AddPageButton.layer.cornerRadius = 32 113 medicineSearchBar.delegate = self 114 searchDataList = medicineDataList 115 tableView.tableFooterView = UIView() 116 tableView.delegate = self 117 tableView.dataSource = self 118 tableView.keyboardDismissMode = .onDrag 119 tableView.register(UINib(nibName:"CustomTableViewCell",bundle:nil), forCellReuseIdentifier: "Cell") 120 self.navigationItem.hidesBackButton = true 121 } 122 123 124 override func viewWillAppear(_ animated: Bool) { 125 super.viewWillAppear(animated) 126 tableView.keyboardDismissMode = .onDrag 127 getData() 128 } 129 130 131 132 //画面をタッチしたらキーボードを閉じる 133 override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { 134 self.view.endEditing(true) 135 } 136 //検索フォームを押した時の処理 137 func searchBarSearchButtonClicked(_ searchBar: UISearchBar) { 138 searchBar.resignFirstResponder() 139 self.view.endEditing(true) 140 searchBar.showsCancelButton = true 141 DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) { 142 143 if let text = searchBar.text { 144 if text == "" { 145 self.searchDataList = self.medicineDataList 146 self.tableView.reloadData() 147 }else{ 148 self.searchDataList = self.medicineDataList.filter{ (data) -> Bool in 149 return (data.examinationData?.contains(text))! 150 } 151 self.tableView.reloadData() 152 } 153 } 154 } 155 } 156 //キャンセルボタンの処理 157 func searchBarCancelButtonClicked(_ searchBar: UISearchBar) { 158 searchBar.showsCancelButton = false 159 self.view.endEditing(true) 160 medicineSearchBar.text = "" 161 self.tableView.reloadData() 162 } 163 //キャンセルボタンを表示させる処理 164 func searchBarShouldBeginEditing(_ searchBar: UISearchBar) -> Bool { 165 searchBar.showsCancelButton = true 166 return true 167 } 168 169 170 171 172 173 174 @IBAction func AddPageButton(_ sender: Any) { 175 let AddViewController = self.storyboard?.instantiateViewController(withIdentifier: "AddViewController") as! AddViewController 176 self.navigationController?.pushViewController(AddViewController, animated: true) 177 } 178 179 func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 180 if medicineSearchBar.text! == ""{ 181 return medicineDataList.count 182 }else { 183 return searchDataList.count 184 } 185 } 186 187 188 func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 189 let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! CustomTableViewCell 190 191 let medicalList = self.medicineDataList[indexPath.row] 192 let searchList = self.searchDataList[indexPath.row] 193 let photo = UIImage(named: "(String(describing: medicalList.photoData))") 194 195 if medicineSearchBar.text! == ""{ 196 197 cell.examinationName.text = medicalList.examinationData 198 cell.hospitalName.text = medicalList.hospitalData 199 cell.timeLabel.text = medicalList.time 200 cell.imagePageButton.image != nil ? cell.imagePageButton.setImage( photo, for: .normal) : cell.imagePageButton.setImage( image, for: .normal) 201 202 }else{ 203 204 cell.examinationName.text = searchList.examinationData 205 cell.hospitalName.text = searchList.hospitalData 206 cell.timeLabel.text = searchList.time 207 208 if cell.imagePageButton.image != nil{ 209 cell.imagePageButton.setImage( photo, for: .normal) 210 }else{ 211 cell.imagePageButton.setImage( image, for: .normal) 212 } 213 } 214 return cell 215 } 216 217 func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { 218 return 85 219 } 220 } 221 222

試したこと

ここに問題に対して試したことを記載してください。

補足情報(FW/ツールのバージョンなど)

ここにより詳細な情報を記載してください。

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

hoshi-takanori

2021/09/13 18:03

medicineDataList がデータ全件で、searchDataList はそのうち検索に引っかかったものだと思いますが、cellForRowAt の中では無条件で medicineDataList と searchDataList の両方にアクセスしてるので、検索キーワードが空の時にはエラーになるでしょうね。medicineDataList と searchDataList のどっちを使うかの場合分けの条件もたぶんおかしいし…。medicineDataList は検索結果の絞り込みだけに使って、他は searchDataList に統一するのがいいと思います。
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

まだ回答がついていません

会員登録して回答してみよう

アカウントをお持ちの方は

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.49%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問