3

I'm new to Swift.. (And its my first post here!)

I'm using Swift 4 with Xcode 9 and I'm actually trying to save a variable that contains structure to a file, and then reload it again into that variable.

Here is the data I want to save:

var MyVar = [
structure(data1: "48.1", data2: "-10.1", Name: "aaa", Date: "2013-12-01 03:22:32", Age: 20),
structure(data1: "47.7", data2: "-79.2", Name: "bbb", Date: "2011-10-15 12:58:45", Age: 21),
structure(data1: "50.5", data2: "75.8", Name: "ccc", Date: "2014-05-24 02:42:25", Age: 35),
structure(data1: "48.7", data2: "78.5", Name: "ddd", Date: "2017-10-10 15:56:13", Age: 5)]

could you please tell me the easiest way to save and reload this variable?

Ahmad F
  • 30,560
  • 17
  • 97
  • 143
Pascal N
  • 77
  • 6
  • for things like that you should use a database (like [realm](https://realm.io/docs/swift/latest/)) – Sandu Apr 26 '18 at 13:04
  • 1
    Possibly Related: https://stackoverflow.com/questions/33637377/how-to-save-an-array-of-custom-structs-to-plist-swift – Ahmad F Apr 26 '18 at 13:06

2 Answers2

1
  1. Make the type of your structure conform to Codable protocol
  2. Use PropertyListEncoder to encode and decode to property list
  3. Store that property list to the file system.

See https://developer.apple.com/documentation/foundation/archives_and_serialization/encoding_and_decoding_custom_types

Marmoy
  • 8,009
  • 7
  • 46
  • 74
  • 1
    Thanks, after a lot of learning on different web site i finally make it work with your instruction..! – Pascal N Apr 27 '18 at 11:31
0

You might want to use local JSON file that holds your data. You can then use Swift 4 Codable / Decodable to load that file.

You will also be able to save it back to a local JSON if you want to.

Is that what you want to do?

Dan Korkelia
  • 104
  • 6