UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

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!

2      

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.

2      

BUILD THE ULTIMATE PORTFOLIO APP Most Swift tutorials help you solve one specific problem, but in my Ultimate Portfolio App series I show you how to get all the best practices into a single app: architecture, testing, performance, accessibility, localization, project organization, and so much more, all while building a SwiftUI app that works on iOS, macOS and watchOS.

Get it on Hacking with Swift+

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

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

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.