Last active
June 26, 2019 06:17
-
-
Save yanil3500/f2d459bdc0dfe4ad6ff9c31044fbc3ef to your computer and use it in GitHub Desktop.
[Saving Swift Custom Data Types To Disk] Code for saving objects to disk in Swift.
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
import Foundation | |
// NOTE: The objects you wish to save to disk must conform to the Codable protocol | |
class Todo: Codable { | |
let name: String | |
private(set) var done: Bool = false | |
init(name: String) { | |
self.name = name | |
} | |
func toggleDone() { | |
done = !done | |
} | |
} | |
do { | |
var todos = [Todo]() | |
// MARK: Saving to/loading from disk | |
let dataFilePath : URL! = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first?.appendingPathComponent("Todos.plist") | |
func save() { | |
let encoder = PropertyListEncoder() | |
if let data = try? encoder.encode(todos) { | |
do { | |
try data.write(to: dataFilePath) | |
} catch { | |
print("Error enconding todos array: \(error)") | |
} | |
} | |
} | |
func load() { | |
if let data = try? Data(contentsOf: dataFilePath){ | |
let decoder = PropertyListDecoder() | |
do { | |
todos = try decoder.decode([Todo].self, from: data) | |
} catch { | |
print("Error decoding todos array") | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment