Hello,
When doing the challange for HotProspects(Day 85) i was writing the initializer and save method like this, basically copying from the bucketlist project and this worked fine from what i can see.
let savePath = FileManager.documentsDirectory.appendingPathComponent("SavedData")
init() {
do {
let data = try Data(contentsOf: savePath)
people = try JSONDecoder().decode([Prospect].self, from: data)
} catch {
people = []
}
}
private func save() {
do {
let data = try JSONEncoder().encode(people)
try data.write(to: savePath, options: [.atomicWrite, .completeFileProtection])
} catch {
print("Unable to save data: \(error.localizedDescription)")
}
}
Paul however did it like this:
let saveKey = "SavedData"
init() {
if let data = try? Data(contentsOf: savePath {
if let decoded = try? JSONDecoder().decode([Prospect].self, from: data) {
people = decoded
return
}
}
// No saved data, empty array by default
people = []
}
private func save() {
if let encoded = try? JSONEncoder().encode(people) {
try? encoded.write(to: savePath, options: [.atomic, .completeFileProtection])
}
}
So the code from the Bucketlist is with a "do-catch" block and the one from HotProspects is with if statements, please correct me if im wrong.
To my question then, is there a profound difference here or are both as viable ?
Thanks in advance! Also, first time i write on the forum so if anything is wrong with the copy and pasted code you know why x)