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

Custom initialisers, what to put when you want you create an empty class?

Forums > Swift

Hello everyone, hope you are doing well,

I have a class here

class Person: Codable, ObservableObject {
    enum Codingkeys: CodingKey {
        case correctAnswers
        case completedAnswers
    }
    @Published var correctAnswers = 0
    @Published var completedAnswers = 0
       // 17:26 11/12 Bucketlist

    required init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: Codingkeys.self)
        correctAnswers = try container.decode(Int.self, forKey: .correctAnswers)
        completedAnswers = try container.decode(Int.self, forKey: .completedAnswers)
    }

    func encode(to encoder: Encoder) throws {
        var container = encoder.container(keyedBy: Codingkeys.self)
        try container.encode(correctAnswers, forKey: .correctAnswers)
        try container.encode(completedAnswers, forKey: .completedAnswers)
    }
}

and this

    init() {
        do {
            let data = try Data(contentsOf: savePath)
            persons = try JSONDecoder().decode(Person.self, from: data)
        } catch {
            persons = Person(from: <#T##Decoder#>) // HERE!!!!!!(I Hope you can see)
        }
    }
}

What do I put after the 'from:' after I have caught an error to create a new empty one (is this even possible?). If this isn't possible could someone please tell me what to have here instead?

Thankyou in advance!

   

Why would you want to create an instance of persons, what would it mean in this case?

Normaly you would either print an error messge (especially useful during debugging), call a fatalError if your app should not proceed further in this condition, or throw an error that is handled by the calling function, if the error is handlable and your app can continue albeit without this action being completed.

   

Hacking with Swift is sponsored by Emerge

SPONSORED Why are Swift reference types bad for app startup time, and what’s the performance cost of protocol conformances? That’s just a couple of the topics you can learn about on the Emerge blog — written by the app performance experts behind Emerge’s advanced app optimization and monitoring tools, based on their experience of working at companies like Apple, Airbnb, Snap, and Spotify.

Find out more

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.