首页 > 解决方案 > split[5] = "00" 当它应该是 "0"

问题描述

我有一个允许用户编辑行条目的 tableView 方法。但是,当我第二次编辑行条目时,我得到一个索引超出范围错误。

正如您在第 679 行(来自图像链接)中看到的,存在由超出范围索引引起的致命错误。当我将光标悬停在“split”关键字上时,xCode 说有 7 个值(0-6)。但是我知道应该有 8 个,因为如果您查看调试窗口并计算 2 个冒号分隔符之间的字符串,您将得到 8 个值 (0-7)。

如果我将光标放在第 676 行(来自图像链接),split[5],字符串值中似乎有两个数字(双零),而应该总是只有一个数字。双零之一应该在 split[6] 中,并且 split[6] 当前具有应该是 split[7] 的值。当 Split[7] 应该具有语言字符串的名称时,它没有赋值,因此它超出了索引范围。

我添加了第 671-672 行,以防它有所帮助但没有任何区别。

func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
        let delete = UIContextualAction(style: .destructive, title: "Delete") {
            (action, sourceView, completionHandler) in
            if let defaults = UserDefaults(suiteName: "group.co.uk.tirnaelectronics.hyperpolyglot.todayview") {
                if var savedWords = defaults.object(forKey: "words") as? [String] {
                    var savedWordIndex = 0
                    for savedWord in savedWords {
                        if savedWord.contains(self.tableViewWords[indexPath.row]) {
                            savedWords.remove(at: savedWordIndex)
                        }
                        savedWordIndex += 1
                    }
                self.words.removeAll()
                self.words = savedWords
                self.saveWords()
                }
            }
            self.tableViewWords.remove(at: indexPath.row)
            tableView.beginUpdates()
            tableView.deleteRows(at: [indexPath], with: .left)
            tableView.endUpdates()
            // delete item at indexPath

            self.resetEnableDisable()
            self.chosenLanguageLoad()
            self.clearEnableDisable()
            self.chosenLanguageLoad()
            self.sortEnableDisable()
            completionHandler(true)
        }

        let edit = UIContextualAction(style: .normal, title: "Edit") {
            (action, sourceView, completionHandler) in
            let ac = UIAlertController(title: "Edit word", message: nil, preferredStyle: .alert)

            // add two text fields, one for English and one for foreign word
            ac.addTextField { textField in
                let tableViewWord = self.tableViewWords[indexPath.row]
                let split = tableViewWord.components(separatedBy: "::")
                let englishWord = split[0]
                textField.placeholder = "\(englishWord)"
            }

            ac.addTextField { (textField) in
                let tableViewWord = self.tableViewWords[indexPath.row]
                let split = tableViewWord.components(separatedBy: "::")
                let foreignWord = split[1]
                textField.placeholder = "\(foreignWord)"
            }

            // create an "Edit Word" button that submits the user's input
            let submitAction = UIAlertAction(title: "Edit Word", style: .default) { [unowned self, ac] (action: UIAlertAction!) in
                // pull out the English and foreign words, or an empty string if there was a problem
                let firstWord = ac.textFields?[0].text?.capitalized ?? ""
                let secondWord = ac.textFields?[1].text?.capitalized ?? ""

                guard firstWord.count > 0 && secondWord.count > 0 else { return }
                // edit item at indexPath
                let split = self.tableViewWords[indexPath.row].components(separatedBy: "::")
                _ = split[0]
                _ = split[1]
                let wrongCount = split[2]
                let homeworkWrongCount = split[3]
                let attemptCount = split[4]
                let homeworkAttemptCount = split[5]
                let homeworkSet = split[6]
                // Line 677: Thread 1: Fatal Error: Index out of range when an edited word is re-edited.
                let language = split[7]

                self.editDefaultsKey(englishWord: firstWord, foreignWord: secondWord, wrongCount: wrongCount, homeworkWrongCount: homeworkWrongCount, attemptCount: attemptCount, homeworkAttemptCount: homeworkAttemptCount, homeworkSet: homeworkSet, language: language, index: indexPath.row)

                self.tableViewWords.remove(at: indexPath.row)
            self.tableViewWords.insert("\(firstWord)::\(secondWord)::\(wrongCount)::\(homeworkWrongCount)::\(attemptCount)::\(homeworkAttemptCount)\(homeworkSet)::\(language)", at: indexPath.row)

                tableView.beginUpdates()
                tableView.deleteRows(at: [indexPath], with: .automatic)
                tableView.insertRows(at: [indexPath], with: .automatic)
                tableView.endUpdates()

                self.chosenLanguageLoad()
                self.resetEnableDisable()
                self.clearEnableDisable()
                self.sortEnableDisable()
            }

            // add the submit action, plus a cancel button
            ac.addAction(submitAction)
            ac.addAction(UIAlertAction(title: "Cancel", style: .cancel))

            // present the alert controller to the user
            self.present(ac, animated: true)
            completionHandler(true)
        }

        let homework = UIContextualAction(style: .normal, title: "Homework") {
            (action, sourceView, completionHandler) in
            let tableViewWord = self.tableViewWords[indexPath.row]
            print("words in tableView editActionsForRowAt in WordsViewController are: \(self.words)")

            let split = tableViewWord.components(separatedBy: "::")
            if split[6] == "0" {
                let firstWord = split[0]
                let secondWord = split[1]
                let wrongCount = split[2]
                let homeworkWrongCount = split[3]
                let attemptCount = split[4]
                let homeworkAttemptCount = split[5]
                let homeworkSet = "1"
                let language = split[7]

                self.editDefaultsKey(englishWord: firstWord, foreignWord: secondWord, wrongCount: wrongCount, homeworkWrongCount: homeworkWrongCount, attemptCount: attemptCount, homeworkAttemptCount: homeworkAttemptCount, homeworkSet: homeworkSet, language: language, index: indexPath.row)

                self.tableViewWords.remove(at: indexPath.row)
            self.tableViewWords.insert("\(firstWord)"+"::"+"\(secondWord)"+"::"+"\(wrongCount)"+"::"+"\(homeworkWrongCount)"+"::"+"\(attemptCount)"+"::"+"\(homeworkAttemptCount)"+"::"+"\(homeworkSet)"+"::"+"\(language)", at: indexPath.row)
                print("Homework set button tapped")
            } else {
                let firstWord = split[0]
                let secondWord = split[1]
                let wrongCount = split[2]
                let homeworkWrongCount = split[3]
                let attemptCount = split[4]
                let homeworkAttemptCount = split[5]
                let homeworkSet = "0"
                let language = split[7]

                self.editDefaultsKey(englishWord: firstWord, foreignWord: secondWord, wrongCount: wrongCount, homeworkWrongCount: homeworkWrongCount, attemptCount: attemptCount, homeworkAttemptCount: homeworkAttemptCount, homeworkSet: homeworkSet, language: language, index: indexPath.row)

                self.tableViewWords.remove(at: indexPath.row)
            self.tableViewWords.insert("\(firstWord)"+"::"+"\(secondWord)"+"::"+"\(wrongCount)"+"::"+"\(homeworkWrongCount)"+"::"+"\(attemptCount)"+"::"+"\(homeworkAttemptCount)"+"::"+"\(homeworkSet)"+"::"+"\(language)", at: indexPath.row)
                print("Homework unset button tapped")
            }
            completionHandler(true)
        }

        delete.backgroundColor = UIColor.systemRed
        edit.backgroundColor = UIColor.systemBlue
        homework.backgroundColor = UIColor.systemGreen

        let swipeConfiguration = UISwipeActionsConfiguration(actions: [delete, edit, homework])

        return swipeConfiguration
    }

我期望: split[0] = "firstWord" split[1] = "secondWord" split[2] = "0" split[3] = "0" split[4] = "0" split[5] = "0" split[6] = "0" split[7] = "italian" 但我得到:split[0] = "firstWord" split[1] = "secondWord" split[2] = "0" split[3] = "0" split[4] = "0" split[5] = "00" split[6] = "italian" split[7] = no value (Thread 1: fatal error: index out of range)

标签: swiftsplit

解决方案


看来这只是一个缺少::. 尝试替换这个:

  self.tableViewWords.insert("\(firstWord)::\(secondWord)::\(wrongCount)::\(homeworkWrongCount)::\(attemptCount)::\(homeworkAttemptCount)\(homeworkSet)::\(language)", at: indexPath.row)

有了这个:

  self.tableViewWords.insert("\(firstWord)::\(secondWord)::\(wrongCount)::\(homeworkWrongCount)::\(attemptCount)::\(homeworkAttemptCount)::\(homeworkSet)::\(language)", at: indexPath.row)

推荐阅读