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!


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 Superwall

SPONSORED Superwall lets you build & test paywalls without shipping updates. Run experiments, offer sales, segment users, update locked features and more at the click of button. Best part? It's FREE for up to 250 conversions / mo and the Superwall team builds out 100% custom paywalls – free of charge.

Learn More

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.