如何将swift结构保存到文件中

时间:2016-06-10 19:50:11

标签: ios swift serialization struct

我想将结构用于我的应用程序的(非常简单的)模型。

但是NSKeyedArchiver只接受对象(扩展NSObjects)。

有没有什么好方法可以将结构保存到文件中?

1 个答案:

答案 0 :(得分:5)

我有时会使用一种非常简单的方法。您需要编写的代码数量不多于类/ NSCoding方案。

首先导入伟大的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
    }
}

让它可以转换为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
    }
}

就是这样。让我们用它

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"