NEW: My new book Pro SwiftUI is out now – level up your SwiftUI skills today! >>

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 RevenueCat

SPONSORED In-app subscriptions are a pain to implement, hard to test, and full of edge cases. RevenueCat makes it straightforward and reliable so you can get back to building your app. Oh, and it's free if your app makes less than $10k/mo.

Learn 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.