为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

弑天下 2019-10-11 10:51:41
我真的很想在我的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上进行简单尝试?
查看完整描述

3 回答

?
慕侠2389804

TA贡献1719条经验 获得超6个赞

斯威夫特的错误处理(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 {

    let msg = msgSections[indexPath.section].msg[indexPath.row]

    // ...

}

(或者,正如rmaddy在评论中说的那样-调查为什么会发生此问题!它根本不应该发生。)


查看完整回答
反对 回复 2019-10-11
?
翻过高山走不出你

TA贡献1875条经验 获得超3个赞

斯威夫特4:

extension Collection where Indices.Iterator.Element == Index {

    subscript (exist index: Index) -> Iterator.Element? {

        return indices.contains(index) ? self[index] : nil

    }

}

用法:


var index :Int = 6 // or whatever number you need

if let _ = myArray[exist: index] {

   // do stuff

}

要么


var index :Int = 6 // or whatever number you need

guard let _ = myArray[exist: index] else { return }


查看完整回答
反对 回复 2019-10-11
  • 3 回答
  • 0 关注
  • 744 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信