-2

How do I save a custom dictionary in UserDefault, I try through PropertyListEncoder, but I have an error.

    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'
Daniel Storm
  • 17,279
  • 7
  • 80
  • 145
  • 1
    Conform to Encodable like the Error states. – Daniel Storm Jul 13 '20 at 14:55
  • You have already got a solution. Apart from this, You should use camel case while declaring the class or struct. [Swift Naming](https://swift.org/documentation/api-design-guidelines/#naming), [Objective-C Naming](https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/CodingGuidelines/Articles/NamingMethods.html). – TheTiger Jul 13 '20 at 15:04

1 Answers1

0

Error states clearly you have to conform pointDict to Encodable. So just do that.

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

Also, do not use try?, use do try catch and handle the errors that are thrown.

do {
    UserDefaults.standard.set(try PropertyListEncoder().encode(pointsPlane), forKey:"pointsPlane")
} catch { print(error) }
Frankenstein
  • 14,749
  • 4
  • 18
  • 44