首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >无法识别Swift 5中的线程1:致命错误:超出范围的索引

无法识别Swift 5中的线程1:致命错误:超出范围的索引
EN

Stack Overflow用户
提问于 2020-04-04 18:41:21
回答 3查看 45关注 0票数 0

我正在构建一个IOS字典应用程序。我正在创建一个带有viewTable的searchBar,以搜索单词并显示正在键入的搜索结果。例如,如果用户输入"app",viewTable应该显示"app,apple,apply“等。下面是我所拥有的,请帮助,谢谢。

代码语言:javascript
复制
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()
   }
}
EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2020-04-04 19:39:28

首先,如果搜索字段为空,则必须处理该案件。

还有一种更高效、更可靠的语法来过滤数组:range(of可以同时过滤不区分大小写和从字符串开始(anchored)开始。

代码语言:javascript
复制
extension ViewController: UISearchBarDelegate {
    func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
        if searchText.isEmpty {
            searching = false
            wordSearch.removeAll()
        } else {
            wordSearch = wordArray.filter{ $0.range(of: searchText, options: [.caseInsensitive, .anchored]) != nil }
            searching = true
        }
        tableView.reloadData()
   }
}

要修复错误,您必须从wordSearchwordArray获取数据,这取决于searching。将numberOfRowsInSectioncellForRowAt替换为

代码语言:javascript
复制
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
}
票数 0
EN

Stack Overflow用户

发布于 2020-04-04 18:46:41

设置数组的计数。

代码语言:javascript
复制
if searching {
  return wordArray.count

并在这里索引其他的一个

代码语言:javascript
复制
if searching {
   cell?.textLabel?.text = wordSearch[indexPath.row] //Thread 1: Fatal error: Index out of range

所以用吧

代码语言:javascript
复制
if searching {
  return wordSearch.count
} else {
  return wordArray.count
}

随同

代码语言:javascript
复制
if searching {
     cell?.textLabel?.text = wordSearch[indexPath.row] //Thread 1: Fatal error: Index out of range
} else {
    cell?.textLabel?.text = wordArray[indexPath.row]
}
票数 0
EN

Stack Overflow用户

发布于 2020-04-04 19:11:45

代码语言:javascript
复制
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
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61033053

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档