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?
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.
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
}
}
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
}
}
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With