Search code examples
arraysswiftsaveloadstructure

Swift 4 : how to write/load structure from file


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?


Solution

    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