arrays - fatal error : Index out of Range Swift 3. 1

标签 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) {
}

最佳答案

除了 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 :索引超出范围而崩溃, 例如,你可以添加一个 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'

关于arrays - fatal error : Index out of Range Swift 3. 1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44104972/

相关文章:

c - 在 C : square brackets vs. 指针中传递数组

swift - 使 "NSManaged public var"成为可选的 bool 值

ios - [NSDecimalNumber 保留] : message sent to deallocated instance 0x174222220, 但为什么呢?

c - 如何读取 C 中以空格分隔的 0-9 数字?

python - 数组上的 Cython 最小值和最大值

ios - 应该使用哪个 UICollectionView 函数来更新单元格中的 UILabel?

php - 用于将图像上传到 sftp 的特定 php 和 swift 代码

ios - 如何将 CloudKit 记录数据从 "TableView-Controller B"传递到 "View-Controller C"?

ios - 如何将 Smooch 的聊天 UI 放入弹出窗口中?

c - 返回整数时出现段错误