Swift 单元格的表视图cellForRowAt中的索引超出范围

Swift 单元格的表视图cellForRowAt中的索引超出范围,swift,Swift,我有一个视图控制器,可以显示歌曲和艺术家。每当我运行代码时,它都会给我一个线程1:致命错误:索引超出艺术家的范围。我试图从我的sql数据库中的两个表中获取信息,它们被称为搜索和艺术家。我做了和搜索一样的事情,它也能工作,但现在我加入了艺术家,我崩溃了。任何帮助都将不胜感激 var searchActive: Bool = false var search = [Search]() var artist = [Artist]() func tableView(_ tableView: UITab

我有一个视图控制器,可以显示歌曲和艺术家。每当我运行代码时,它都会给我一个线程1:致命错误:索引超出艺术家的范围。我试图从我的sql数据库中的两个表中获取信息,它们被称为搜索和艺术家。我做了和搜索一样的事情,它也能工作,但现在我加入了艺术家,我崩溃了。任何帮助都将不胜感激

var searchActive: Bool = false
var search = [Search]()
var artist = [Artist]()

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for:  indexPath)
    
    if  (searchActive) {
        cell.textLabel?.text = search[indexPath.row].cleanName
        cell.textLabel?.text = artist[indexPath.row].artistName //CRASH
    } else {
       searchActive = true
    }
    return cell;
}
  
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    
    return search.count;
}
搜索栏功能:

   func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
    search = search.filter({ (song) -> Bool in
       return song.cleanName.range(of: searchText, options: .caseInsensitive) != nil
   })
    artist = artist.filter({ (artists) -> Bool in
        return artists.artistName.range(of: searchText, options: .caseInsensitive) != nil
    })
    
    if (artist.count == 0) {
        searchActive = false
    } else {
        searchActive = false
    }
    if(search.count == 0) {
        searchActive = false
    } else {
        searchActive = false
    }
    

试试这个。它不会崩溃,因为如果数组为零或没有数据,它将得到管理。在
numberofrowsinssection
中使用了三元条件,其中它将设置最大计数,因此它不会在
cellForRowAt indexPath
处崩溃


func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for:  indexPath)
    
    if  (searchActive) {
        cell.textLabel?.text = search[indexPath.row].cleanName
        cell.textLabel?.text = artist[indexPath.row].artistName ?? "No Data"
    } else {
       searchActive = true
    }
    return cell;
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    
   if  (searchActive) {
        return search.count > artist.count ? search.count : artist.count
    }
    else{
        return artist.count 
//Note here you can return anything once your search is not active. or just return 0 to show blank results. 

     }

}

希望它对你有用

它取决于您使用numberOfRows(instation:Int)委托方法返回的行数。然而,您的cellForRowAt方法是有问题的,因为它依赖于两个数组中的任何一个。@ElTomato好的,我编辑了它。我试图修复它,但仍然无法显示numberOfRows委托方法。@ElTomato编辑了它。不要将多个数组用作表视图数据源。它会导致这种错误。重构你的设计