简体   繁体   English

如何将 swift 结构保存到文件

[英]How to save a swift struct to file

I want to use structs for the (very simple) model of my app.我想为我的应用程序的(非常简单的)model 使用结构。

However NSKeyedArchiver only accepts objects (extending NSObjects ).但是NSKeyedArchiver只接受对象(扩展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. 您需要编写的代码数量不超过类/ NSCoding方案。

First of all import the great SwiftyJSON lib. 首先导入伟大的SwiftyJSON库。

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 让它可以转换为JSON或从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"

Updated solution for Swift 5+ Swift 5+ 的更新解决方案

  • No need to import anything无需导入任何东西
  • Make your struct codable使您的结构可编码
struct Starship: Codable { // Add this
    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
    }
}
  • Functions to read from and write to file读取和写入文件的函数
var data: Starship

func readFromFile(filePathURL: URL) throws {
    let readData = try Data(contentsOf: filePathURL)
    self.data = try JSONDecoder().decode(Starship.self, from: readData)
}

func writeToFile(filePathURL: URL) throws {
    let jsonData = try JSONEncoder().encode(self.data)
    try jsonData.write(to: filePathURL)
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM