首页 > 解决方案 > 致命错误:收到我标记为可选的 nil 数据时索引超出范围

问题描述

嗨,我有一些问题与我的数据模型数组中的索引超出范围有关。只要 为images = []空,应用程序就会崩溃。

所以这是我的 UIViewController 的表格视图中的代码。

        
        if let urlString = vehicleList?._embedded.userVehicles[indexPath.row].images[0] {
            
            let url = URL(string: urlString)
            cell.vehicleImage.kf.setImage(with: url, placeholder: nil)
        } else {
            let url = URL(string: "https://vehicleimage-insure.s3-eu-west-1.amazonaws.com/defaultCarIcon.png")
            cell.vehicleImage.kf.setImage(with: url, placeholder: nil)
        }

这是我的图像属性数据模型,我已将其标记为可选:

struct UserVehicles: Codable {
    let id: String 
    let images: [String?]
    let userId: String
}

错误信息如下图:

在此处输入图像描述

我检查了调试输出,如下:

在此处输入图像描述

我的意思是我做了 if let 语法,不应该捕获错误吗?请给我一些提示,我该如何解决这个错误?

标签: swiftnulloptionaliso

解决方案


if let 语句将检查可选语句是否为 nil。

当您尝试访问不存在索引处的数组元素时,它不会返回 nil 但您会收到索引超出范围错误。

如果您想安全地访问数组中的元素,您应该在访问索引之前执行数组大小检查。

if list.count > 0 {
    let listItem = list[0]
    // do something
}

或者实现 Collection 的扩展以安全访问。

extension Collection {

    /// Returns the element at the specified index if it is within bounds, otherwise nil.
    /// Sample: `list[safe: index]`
    subscript (safe index: Index) -> Element? {
        return indices.contains(index) ? self[index] : nil
    }
}

那么你可以使用 if let ,因为这个下标将返回一个可选的。

if let listItem = list[safe: 0] {
    // do something
}

推荐阅读