How to save a swift struct to file

2019-03-31 05:14发布

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?

1条回答
2楼-- · 2019-03-31 05:47

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"
查看更多
登录 后发表回答