You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将UserDefaults中存储的字典数组数据显示到TableView,取值为nil如何解决

问题原因

  1. 类型转换错误:你尝试将取出的元素转换为[String:String]类型,但从实际打印的数组内容可见,商品数据是多层嵌套结构,包含数组、嵌套字典、空值等多种类型,并非所有值均为字符串,因此该转换必然失败返回nil。
  2. 可选值未正确处理:数组中存储的元素为可选类型,未先解包就直接进行类型转换也会提升失败概率。

修复方案

临时修复(沿用现有字典存储逻辑)

将相关代码替换为以下写法:

// 数组声明修改为存储非可选字典类型
var favouritesArray: [[String: Any]] = []

// 读取数据时做安全类型转换
if let savedData = AppUtility.getCustomObjectOfKey(key: "wishlist") as? [Any] {
    // 过滤掉无效元素,只保留字典类型的有效数据
    favouritesArray = savedData.compactMap { $0 as? [String: Any] }
}

// cell复用与取值逻辑修正
guard let cell = self.wishlistTableView.dequeueReusableCell(withIdentifier: "wishlistCell") as? WishlistTableViewCell else {
    return UITableViewCell()
}
let rowData = favouritesArray[indexPath.row]
// 取出Product对应的商品信息字典
guard let productInfo = rowData["Product"] as? [String: Any] else {
    return cell
}
// 按需取对应字段即可,示例:
let productTitle = productInfo["title"] as? String
if let variants = productInfo["variants"] as? [[String: Any]], 
   let firstVariant = variants.first, 
   let price = firstVariant["price"] as? String {
    print(price)
}

优化方案(推荐)

建议让你的模型类遵守Codable协议,存储时将模型序列化为Data存入UserDefaults,读取时直接反序列化为模型数组,无需手动处理字典类型转换,可从根源上避免这类类型不匹配的问题。

内容的提问来源于stack exchange,提问作者Ahmed Ayoub

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 07:45:00