首页 > 解决方案 > 在 UserDefault 问题中保存自定义字典

问题描述

如何在 UserDefault 中保存自定义字典,我尝试通过 PropertyListEncoder,但出现错误。

    struct pointDict {
          let id: Int
          let name: String
          let type: Int8   
      }

    var pointsPlane: [pointDict] = []

    ...

    UserDefaults.standard.set(try? PropertyListEncoder().encode(pointsPlane), forKey:"pointsPlane")

Class 'PropertyListEncoder' requires that 'ViewControllerPlane.pointDict' conform to 'Encodable'

标签: swift

解决方案


错误表明您必须pointDict遵守Encodable. 所以就这样做吧。

struct PointDict: Encodable { // also make struct model name's first letter uppercased.
    let id: Int
    let name: String
    let type: Int8
}

另外,不要使用try?、使用do try catch和处理抛出的错误。

do {
    UserDefaults.standard.set(try PropertyListEncoder().encode(pointsPlane), forKey:"pointsPlane")
} catch { print(error) }

推荐阅读