Last active
January 29, 2018 22:13
-
-
Save KrisYu/2a2e8aeafb9e15c6866e54328b424099 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
struct Person: Codable { | |
var firstName: String | |
var lastName: String | |
var name: Data? { | |
return try? PropertyListEncoder().encode(self) | |
} | |
init?(name: Data) { | |
if let newValue = try? PropertyListDecoder().decode(Person.self, from: name) { | |
self = newValue | |
} else { | |
return nil | |
} | |
} | |
// found actually use json to encode and decode would be better | |
// because json would write the data to json format, which is very nice to read | |
var json: Data? { | |
return try? JSONEncoder().encode(self) | |
} | |
init?(json: Data) { | |
if let newValue = try? JSONDecoder().decode(Person.self, from: json) { | |
self = newValue | |
} else { | |
return nil | |
} | |
} | |
init(firstName: String, lastName: String) { | |
self.firstName = firstName | |
self.lastName = lastName | |
} | |
} | |
/// Save file | |
let moi = Person(firstName: "Matt", lastName: "Neuburg") | |
if let moifile = try? FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false).appendingPathComponent("moi.txt"), let name = moi.name{ | |
do { | |
try name.write(to: moifile) | |
print(moifile) | |
print("saved data successfully") | |
} catch let error { | |
print("couldn't save \(error)") | |
} | |
} | |
/// Read file | |
if let moifile = try? FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false).appendingPathComponent("moi.txt"){ | |
do { | |
let persondata = try Data(contentsOf: moifile) | |
let person = Person(name:persondata) | |
print(person) | |
} catch let error { | |
print("couldn't save \(error)") | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment