WWDC22 SALE: Save 50% on all my Swift books and bundles! >>

Day 85 Challange - Writing to the documents directory

Forums > 100 Days of SwiftUI

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)

   

Both work fine, the only difference is that obviously the do - catch version prints out an error message and thus gives you more debugging information if something doesn't work. In a full app you can also use the catch block to give the user an error message or try to recover from it. The try? is basically a short cut.

   

Using try? like in the second example converts the result to an Optional, with the effect of hiding any error that occurs behind a nil value. That may or may not be what you want to do. You would need to evaluate what the function is doing and which method of error handling is appropriate.

   

Ah, thank you very much! =)

   

Hacking with Swift is sponsored by RevenueCat

SPONSORED In-app subscriptions are a pain. The code can be hard to write, hard to test, and full of edge cases. RevenueCat makes it straightforward and reliable so you can get back to building your app.

Explore the docs

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.