致命错误:索引超出范围Swift 3.1

时间:2017-05-22 05:02:32

标签: arrays swift swift3

发生什么事情是当程序试图访问我的txt文件的其他2行时它正在爆炸,当我在数组下查看xcode时,它显示行被" \ t"但它只是不会显示其他2行,而且它令人发狂...请在下面看到我的代码,任何帮助表示赞赏。

var dictDoc = [String:String]()
var docArray = NSMutableArray()

override func viewDidLoad() {
    super.viewDidLoad()

    let path = Bundle.main.path(forResource: "docs", ofType: "txt")
    let fileMgr = FileManager.default
    if fileMgr.fileExists(atPath: path!){
        do{
            let fullText = try String(contentsOfFile: path!, encoding: String.Encoding.utf8)
            let readings = fullText.components(separatedBy: "\n") as [String]
            for i in 1..<readings.count {
                let docData = readings[i].components(separatedBy: "\t")
                dictDoc["Program"] = "\(docData[0])"
                dictDoc["Signature"] = "\(docData[1])"
                dictDoc["Extension"] = "\(docData[2])"
                docArray.add(dictDoc)
            }
        }catch let error as NSError{
            print("Error: \(error)")
        }
        self.title = "Word Processor Programs"
    }
    tableView.dataSource = self
    tableView.delegate = self
}

func numberOfSections(in tableView: UITableView) -> Int {    
    return 1
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return docArray.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
    let doc = docArray[indexPath.row]
    cell.textLabel?.text = "\((doc as AnyObject).object(forKey: "Program")!)"
    cell.detailTextLabel?.text = "\((doc as AnyObject).object(forKey: "Signature")!)    \((doc as AnyObject).object(forKey: "Extension")!)"
    return cell
}

@IBAction func Closebtn(_ sender: UIButton) {
}

1 个答案:

答案 0 :(得分:0)

除了Xcode在复制文本时抱怨一个不可打印的ASCII字符,你的逻辑中有一个微妙的错误:注意最后的换行符。这意味着fullText.components(separatedBy: "\n")为您提供了几乎您想要的内容,但附加的空字符串作为结果数组的最后一个元素。

可能的解决方案:

  • trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)应用于fullText,以便在拆分之前摆脱那个讨厌的换行符。
  • 过滤掉空字符串:let readings = fullText.components(separatedBy: "\n").filter { !$0.isEmpty }

哦,在我看来,API和MS Pub之间的\\应该是换行符:...API\n MS Pub...

<强>更新

为了帮助您在将来跟踪这些错误并防止您的程序因fatal error: Index out of range而崩溃, 例如,您可以添加guard

...
let docData = readings[i].components(separatedBy: "\t")
guard docData.count == 3 else {
    // Ignore, log message, throw error, whatever is appropriate in your use case.
    print("Unexpected format in \(readings[i])")
    continue
}
...

如果不以某种方式处理换行符,则会打印

Unexpected format in ''

我提到的\\也会显示出来:

Unexpected format in ' Acrobat plug-in  4D 5A 90 00 03 00 00 00 API\ MS Pub 58 54   BDR'
相关问题