Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to save a swift struct to file

I want to use structs for the (very simple) model of my app.

However NSKeyedArchiver only accepts objects (extending NSObjects).

Is there any good way to save a struct to a file?

like image 430
PopKernel Avatar asked Jun 10 '16 19:06

PopKernel


1 Answers

A very simple approach I used sometimes. The quantity of code you need to write is no more then in the class/NSCoding scenario.

First of all import the great SwiftyJSON lib.

Let's start with a simple struct

struct Starship {
    let name: String
    let warpSpeed: Bool
    let captain: String?

    init(name: String, warpSpeed: Bool, captain: String? = nil) {
        self.name = name
        self.warpSpeed = warpSpeed
        self.captain = captain
    }
}

Let's make it convertible to/from a JSON

struct Starship {
    let name: String
    let warpSpeed: Bool
    let captain: String?

    init(name: String, warpSpeed: Bool, captain: String? = nil) {
        self.name = name
        self.warpSpeed = warpSpeed
        self.captain = captain
    }

    init?(json: JSON) {
        guard let
            name = json["name"].string,
            warpSpeed = json["warpSpeed"].bool
        else { return nil }
        self.name = name
        self.warpSpeed = warpSpeed
        self.captain = json["captain"].string
    }

    var asJSON: JSON {
        var json: JSON = [:]
        json["name"].string = name
        json["warpSpeed"].bool = warpSpeed
        json["captain"].string = captain
        return json
    }
}

That's it. Let's use it

let enterprise = Starship(name: "Enteriprise D", warpSpeed: true, captain: "JeanLuc Picard")

let json = enterprise.asJSON
let data = try! json.rawData()

// save data to file and reload it

let newJson = JSON(data: data)
let ship = Starship(json: newJson)
ship?.name // "Enterprise D"
like image 137
Luca Angeletti Avatar answered Sep 22 '22 07:09

Luca Angeletti