我试图根据在搜索栏中搜索到的内容更新tableView。我有三个要更新的标签,因此当用户搜索名称时,似乎每个学校的数据都是正确的。但是我总是收到一个致命错误,说索引超出范围,但是索引是1。我一直在打印索引,并且数组中有两个以上的对象。数据是从api接收的,并且数据显示得很好,就在我尝试搜索时。
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int)-> Int {
if searching {
return searchCollege.count
}
else {
return resultArray.count
}
}
}
extension ViewController: UISearchBarDelegate {
func searchBar(_ searchBar: UISearchBar, textDidChange searchText:String){
let collegeNames = resultArray.map{$0.userSchool_name}
names = collegeNames.filter({$0!.prefix(searchText.count) == searchText}) as! [String]
for i in 0...resultArray.count
{
if names.contains(resultArray[i].userSchool_name!){
print("Here's the value of i")
print(i)
**gets caught at this line*** searchCollege[i].schoolName = resultArray[i].userSchool_name!
searchCollege[i].admRate = String(resultArray[i].admission_rate!)
searchCollege[i].actScores = String(resultArray[i].act_Scores_midCum!)
searchCollege[i].satScores = String(resultArray[i].sat_Scores_midCum!)
}
}
if (searchCollege.count == 0) {
self.searchCollege[0].schoolName = "No Result"
self.searchCollege[0].admRate = " "
self.searchCollege[0].actScores = " "
self.searchCollege[0].satScores = " "
}
searching = true
tableView.reloadData()
}
用户速拨
struct Root: Codable {
let results : [Users]
}
struct Users: Codable {
let userSchool_name: String?
let admission_rate: Float64?
let sat_Scores_midCum: Float64?
let act_Scores_midCum: Float64?
enum CodingKeys: String, CodingKey {
case userSchool_name = "school.name"
case admission_rate = "latest.admissions.admission_rate.overall"
case sat_Scores_midCum = "latest.admissions.sat_scores.average.overall"
case act_Scores_midCum = "latest.admissions.act_scores.midpoint.cumulative"
}
}
该for
回路只适用于这两种形式
for i in 0...resultArray.count - 1 { ...
或(推荐)
for i in 0..<resultArray.count { ...
但是还有一种更有效的语法
for (index, element) in resultArray.enumerated()
{
if names.contains(element.userSchool_name!){
print("Here's the value of index", index)
searchCollege[index].schoolName = element.userSchool_name!
searchCollege[index].admRate = String(element.admission_rate!)
searchCollege[index].actScores = String(element.act_Scores_midCum!)
searchCollege[index].satScores = String(element.sat_Scores_midCum!)
}
}
并且请注意,如果searchCollege
为空,您的代码也将可靠地崩溃
编辑:
根据numberOfRowsInSection
方法为什么不简单
func searchBar(_ searchBar: UISearchBar, textDidChange searchText:String){
if searchText.isEmpty {
searchCollege.removeAll()
searching = false
} else {
searchCollege = resultArray.filter{ $0!.userSchool_name.range(of: searchText, options: [.anchored, .caseInsensitive]) != nil }
searching = true
{
tableView.reloadData()
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句