swift - 致命错误:收到我标记为可选的 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 语法,不应该捕获错误吗?请给我一些提示,我该如何解决这个错误?
解决方案
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
}
推荐阅读
- sql - MSSQL:根据条件在列中搜索重复项
- javascript - 用于从父字符串中识别和提取两个不同字符串的正则表达式
- sas - (SAS) 如何使用基于 ID 的数据获取日期?
- python - 如何使 Tesseract 像 pythonic 模块一样工作
- sharepoint - Caml 查询简单 ID
- ios - 在 Xcode 中拉伸图像
- eclipse - WSO2 Integrator 6.3 - 如何从其他项目调用序列?
- pdf - rmarkdown中pdf和word的分页符
- android - 如何在以下结构中更新用户
- jquery - 如何使用 jquery 忽略来自隐藏 Div 中的字段的验证?