How do you persist a Swift struct to disk?

I'd like to have my table view's data save and load from disk whenever the user leaves and reenters the app. I tried conforming to the NSCoding protocol as detailed here, but then got a compiler error saying that non-class types cannot conform to class protocol 'NSCoding'. Any guidance would be appreciated.

Replies

`NSCoding` is based on the runtme of Objective-C class, and you cannot make structs conform to `NSCoding`.


- Convert the struct to Data (NSData in Objective-C), and use `NSCoding` method to archive the class containing the Data.

- Convert the struct (or Array of struct, or some class or struct containing the struct) directly to Data, and store the Data.


`Codable` would be useful, in both cases.


Anyway, please show your actual code. Just showing a link to an old genral guidance would not help you solve your issue.