KakaJSON能夠只用
一行代碼
將經常使用數據進行歸檔\解檔swift
// 文件路徑(String或者URL均可以) let file = "/Users/mj/Desktop/test.data"
let string1 = "123" // 將字符串寫入文件 write(string1, to: file) // 從文件中讀取字符串 let string2 = read(String.self, from: file) XCTAssert(string2 == string1) // 從文件中讀取Int XCTAssert(read(Int.self, from: file) == 123)
let date1 = Date(timeIntervalSince1970: 1565922866) // 將Date寫入文件 write(date1, to: file) // 從文件中讀取Date let date2 = read(Date.self, from: file) XCTAssert(date2 == date1) // 從文件中讀取Int XCTAssert(read(Int.self, from: file) == 1565922866)
let array1 = ["Jack", "Rose"] // 將數組寫入文件 write(array1, to: file) // 從文件中讀取數組 let array2 = read([String].self, from: file) XCTAssert(array2 == array1) // 一樣支持Set、Dictionary等
struct Book: Convertible { var name: String = "" var price: Double = 0.0 } struct Car: Convertible { var name: String = "" var price: Double = 0.0 } struct Dog: Convertible { var name: String = "" var age: Int = 0 } struct Person: Convertible { var name: String = "Jack" var car: Car? = Car(name: "Bently", price: 106.666) var books: [Book]? = [ Book(name: "Fast C++", price: 666.6), Book(name: "Data Structure And Algorithm", price: 666.6), ] var dogs: [String: Dog]? = [ "dog0": Dog(name: "Wang", age: 5), "dog1": Dog(name: "ErHa", age: 3), ] } // 將模型寫入文件 write(Person(), to: file) // 從文件中讀取模型 let person = read(Person.self, from: file) XCTAssert(person?.name == "Jack") XCTAssert(person?.car?.name == "Bently") XCTAssert(person?.car?.price == 106.666) XCTAssert(person?.books?.count == 2) XCTAssert(person?.dogs?.count == 2)
struct Car: Convertible { var name: String = "" var price: Double = 0.0 } let models1 = [ Car(name: "BMW", price: 100.0), Car(name: "Audi", price: 70.0) ] // 將模型數組寫入文件 write(models1, to: file) // 從文件中讀取模型數組 let models2 = read([Car].self, from: file) XCTAssert(models2?.count == models1.count) XCTAssert(models2?[0].name == "BMW") XCTAssert(models2?[0].price == 100.0) XCTAssert(models2?[1].name == "Audi") XCTAssert(models2?[1].price == 70.0)
struct Car: Convertible, Hashable { var name: String = "" var price: Double = 0.0 } let models1: Set<Car> = [ Car(name: "BMW", price: 100.0), Car(name: "Audi", price: 70.0) ] // 將模型Set寫入文件 write(models1, to: file) // 從文件中讀取模型Set let models2 = read(Set<Car>.self, from: file)! XCTAssert(models2.count == models1.count) for car in models2 { XCTAssert(["BMW", "Audi"].contains(car.name)) XCTAssert([100.0, 70.0].contains(car.price)) }
struct Car: Convertible { var name: String = "" var price: Double = 0.0 } let models1 = [ "car0": Car(name: "BMW", price: 100.0), "car1": Car(name: "Audi", price: 70.0) ] // 將模型字典寫入文件 write(models1, to: file) // 從文件中讀取模型字典 let models2 = read([String: Car].self, from: file) XCTAssert(models2?.count == models1.count) let car0 = models2?["car0"] XCTAssert(car0?.name == "BMW") XCTAssert(car0?.price == 100.0) let car1 = models2?["car1"] XCTAssert(car1?.name == "Audi") XCTAssert(car1?.price == 70.0)