0
votes

Impossible d'identifier le fil 1 dans Swift 5: Erreur fatale: Index hors de portée

Je construis une application de dictionnaire iOS. Je crée une vieilletable avec une barre de recherche pour rechercher les mots et afficher les résultats de la recherche comme saisi. Par exemple, si les types d'utilisateurs dans "App" ", la vieilletable doit afficher" App, Apple, Appliquer ", etc. Heres ce que j'ai, s'il vous plaît aider et merci.

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var searchBar: UISearchBar!
    @IBOutlet weak var tableView: UITableView!

    var wordSearch = [String]()
    var searching = false
    var wordArray: [String] = []

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.

        let url = Bundle.main.url(forResource: "words_alpha", withExtension: "txt")! // file URL for file "words_alpha.txt"
               do {
                   let string = try String(contentsOf: url, encoding: .utf8)
                   wordArray = string.components(separatedBy: CharacterSet.newlines)
               } catch {
                   print(error)
               }
    }
}

extension ViewController: UITableViewDataSource, UITableViewDelegate {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if searching {
            return wordArray.count
        } else {
            return wordArray.count
        }

    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell");cell?.textLabel?.text = wordArray[indexPath.row]
        if searching {
            cell?.textLabel?.text = wordSearch[indexPath.row] //Thread 1: Fatal error: Index out of range
        } else {
            cell?.textLabel?.text = wordSearch[indexPath.row]
        }
            return cell!
        }
    }

extension ViewController: UISearchBarDelegate {
    func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
        wordSearch = wordArray.filter({$0.prefix(searchText.count) == searchText;})
        searching = true
        tableView.reloadData()
   }
}


0 commentaires

3 Réponses :


0
votes

Vous définissez un nombre de tableau xxx pré>

et indexez l'autre 1 ici p> xxx pré>

alors utilisez p>

if searching {
     cell?.textLabel?.text = wordSearch[indexPath.row] //Thread 1: Fatal error: Index out of range
} else {
    cell?.textLabel?.text = wordArray[indexPath.row]
}


1 commentaires

Merci. Il n'y a pas d'erreur, cependant, la vision de la table est vide lorsque je commence à taper la barre de recherche sur le simulateur. Il semble que le tableau soit vide. une idée?



0
votes
The above answer is right . 

Adding to it. The search filtering g method seems to be wrong

func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
        **wordSearch = wordArray.filter({$0.prefix(searchText.count) == searchText;})**
        searching = true
        tableView.reloadData()
   }

Instead use **wordArray.filter({$0.contains(searchText)})**

And on clearing the search bar . Reset searching = false and empty the wordSearch array.
Check whether you need to set the searchBar.delegate = self in viewDidLoad.

0 commentaires

0
votes

Tout d'abord, vous devez gérer le cas si le champ de recherche est vide.

et il existe une syntaxe plus efficace et fiable pour filtrer la gamme: de la plage (de code> peut filtrer insensibles à filtrer insensibles et à partir du début de la chaîne ( ancré code>) simultanément. p> xxx pré>

pour corriger l'erreur que vous devez obtenir les données de wordsarch ou Wordarray code> en fonction de Recherche code>. Remplacer NumberfrowSectionSection code> et celltforat code> avec p>

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return searching ? wordSearch.count : wordArray.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for indexPath)
    let word = searching ? wordSearch[indexPath.row] : wordArray[indexPath.row]
    cell.textLabel?.text = word
    return cell
}


1 commentaires

MERCI! J'avais des difficultés avec la capitalisation, vous êtes génial.