如何在Swift中捕获“索引超出范围”?

我真的很想在我的Swift代码中使用一个更简单的经典try catch块,但是我找不到能做到这一点的任何东西。


我只需要:


try {

// some code that causes a crash.

}

catch {

// okay well that crashed, so lets ignore this block and move on.

}  

这是我的难题,当TableView重新加载新数据时,某些信息仍位于RAM中,该信息会调用didEndDisplayingCell具有新的空数据源的tableView崩溃。


所以我经常抛出异常 Index out of range


我已经试过了:


func tableView(tableView: UITableView, didEndDisplayingCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {


    do {

        let imageMessageBody = msgSections[indexPath.section].msg[indexPath.row] as? ImageMessageBody

        let cell = tableView.dequeueReusableCellWithIdentifier("ImageUploadCell", forIndexPath: indexPath) as! ImageCell

        cell.willEndDisplayingCell()

    } catch {

        print("Swift try catch is confusing...")

    }

}

我也尝试过这个:


func tableView(tableView: UITableView, didEndDisplayingCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {

    print(indexPath.section)

    print(indexPath.row)


    if msgSections.count != 0 {

        if let msg = msgSections[indexPath.section].msg[indexPath.row] as? ImageMessageBody {

            let cell = tableView.dequeueReusableCellWithIdentifier("ImageUploadCell", forIndexPath: indexPath) as! ImageCell

            cell.willEndDisplayingCell()

        }

    }

}

这是一个优先级很低的代码块,我花了很多时间进行反复试验,弄清楚swift内置的哪种错误处理程序适用于在我有成千上万种类似情况的情况下极其独特的情况。代码可能会崩溃,并且不会对用户体验产生任何影响。


简而言之,我不需要任何花哨的东西,但是Swift似乎有非常具体的错误处理程序,这些错误处理程序根据我是从函数返回值中获取值还是从数组索引中获取不存在的值而有所不同。


是否像其他流行编程语言一样,可以在Swift上进行简单尝试?


弑天下
浏览 747回答 3
3回答

慕侠2389804

斯威夫特的错误处理(do/ try/ catch)是不是要解决运行时异常,如“索引超出范围”。运行时异常(您可能还会看到称为trap,致命错误,断言失败等)是程序员错误的标志。除了内部-Ounchecked版本,Swift通常保证这些会使您的程序崩溃,而不是继续在错误/未定义状态下执行。这类崩溃可能是由于强制展开!,隐式展开,unowned引用滥用,溢出,fatalError()s和precondition()s及assert()s等导致的整数运算/转换(以及不幸的是,Objective-C异常)引起的。解决方法是简单地避免这些情况。在您的情况下,检查数组的边界:if indexPath.section < msgSections.count && indexPath.row < msgSections[indexPath.section].msg.count {&nbsp; &nbsp; let msg = msgSections[indexPath.section].msg[indexPath.row]&nbsp; &nbsp; // ...}(或者,正如rmaddy在评论中说的那样-调查为什么会发生此问题!它根本不应该发生。)

翻过高山走不出你

斯威夫特4:extension Collection where Indices.Iterator.Element == Index {&nbsp; &nbsp; subscript (exist index: Index) -> Iterator.Element? {&nbsp; &nbsp; &nbsp; &nbsp; return indices.contains(index) ? self[index] : nil&nbsp; &nbsp; }}用法:var index :Int = 6 // or whatever number you needif let _ = myArray[exist: index] {&nbsp; &nbsp;// do stuff}要么var index :Int = 6 // or whatever number you needguard let _ = myArray[exist: index] else { return }
打开App,查看更多内容
随时随地看视频慕课网APP