ios - 如何在 Swift 中捕获 "Index out of range"?

标签 ios swift uitableview

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

我只需要:

try {
// some code that causes a crash.
}
catch {
// okay well that crashed, so lets ignore this block and move on.
}  

这是我的困境,当 TableView 重新加载新数据时,一些信息仍然位于 RAM 中,这些信息在带有新空数据源的 tableView 上调用 didEndDisplayingCell 会崩溃。

所以我经常抛出异常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 上有像其他流行编程语言一样简单的 try catch 吗?

最佳答案

正如评论和其他答案中所建议的,最好避免这种情况。但是,在某些情况下,您可能想要检查数组中是否存在某个项目以及是否安全地返回该项目。为此,您可以使用下面的数组扩展来安全地返回数组项。

swift 5

extension Collection where Indices.Iterator.Element == Index {
    subscript (safe index: Index) -> Iterator.Element? {
        return indices.contains(index) ? self[index] : nil
    }
}

swift 4

extension Collection where Indices.Iterator.Element == Index {
    subscript (safe index: Index) -> Iterator.Element? {
        return indices.contains(index) ? self[index] : nil
    }
}

swift 3

extension Collection where Indices.Iterator.Element == Index {
    subscript (safe index: Index) -> Generator.Element? {
        return indices.contains(index) ? self[index] : nil
    }
}

swift 2

extension Array {
    subscript (safe index: Int) -> Element? {
        return indices ~= index ? self[index] : nil
    }
}
  • 这样您就永远不会击中 Index out of range
  • 您必须检查该商品是否为 nil

引用this question了解更多

<小时/>

Trying the Swift3 code in a Playground in Xcode 8.3.2 still leads to a "crash" when I do let ar = [1,3,4], then let v = ar[5]. Why? – Thomas Tempelmann May 17 at 17:40

您必须使用我们定制的下标,而不是 let v = ar[5] ,它将是let v = ar[safe: 5] .

默认从数组获取值。

let boo = foo[index]

添加使用自定义下标。

let boo = fee[safe: index]

// And we can warp the result using guard to keep the code going without throwing the exception.
guard let boo = foo[safe: index] else {
  return
}

关于ios - 如何在 Swift 中捕获 "Index out of range"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41692284/

相关文章:

iphone - UIView 中的 UITableViewController

ios - NSSortDescriptor 问题

ios - 如何从 iOS Swift 3 的键盘上删除更改语言键按钮

ios - 关闭 View 时更改值

ios - 动态宽度大小以适应 stackview 中的控件

iphone - 如何确定 UISearchDisplayController 是否为 searchResults TableView 可见?

ios - 提议的 Destination IndexPath 由于 header 错误

java - C++ IO 与 Java IO

ios - 分配 : *** error for object: Invalid pointer dequeued from free list *** set a breakpoint in malloc_error_break to debug in Magical record IOS

Swift - 如何允许人们设置自己的 Firebase 后端?