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/37222811/

相关文章:

ios - 带有 gif 图像的 MBProgressHud

objective-c - 为什么在不设置断点的情况下程序会暂停而不崩溃?

swift - 在数据显示之前等待 1-2 秒从 Firebase 获取数据 (IOS)

ios - 将新行插入 UITableView 中的新部分的动画

ios - 谷歌地图 ios 中心的 Objective C 固定标记

objective-c - 触摸绘制和删除线条

ios - 如何消除我的 CABasicAnimation 中的 "jump"?

xcode - 隐藏 UICollectionViewCell 中的 View

ios - 查找哪个单元格被单击并执行 Segue

ios - 对于 viewForHeaderInSection 中的自定义单元格,重新加载特定的 viewForHeaderInSection IOS