Andrey Isaev
Andrey Isaev

Reputation: 192

How to redefine default class init() in extension in Swift?

I've already got a class description for todo list app like following:

class TaskStore: ObservableObject {
    @Published var tasks: Task = [
        Task("Programm app"),
        Task("Clean up apartment",
        Task("Buy NY gifts")
        Task("Decorate Christmas tree")
    ]
}

I want to redefine its initialiser using extension (without touching previous code) to be able either to read already existing todos from .json file or init by default like following:

extension TaskStore {
    var storedTasks: [Task]? {
        // Code for downloading from .json file 
    }

    init() {
        if let storedTasks = self.storedTasks {
            self.tasks = self.storedTasks
        }
    }
 }

The problem is that XCode compiler does not allow to place either convenience init() or designated init() in the extension as there is no init() defined in the class description.

Please help to (re)define init() in extension.

Upvotes: 1

Views: 1252

Answers (1)

Maysam
Maysam

Reputation: 7367

You cannot do that.

Extensions add new functionality to an existing class, structure, enumeration, or protocol type. This includes the ability to extend types for which you do not have access to the original source code (known as retroactive modeling). Extensions are similar to categories in Objective-C. (Unlike Objective-C categories, Swift extensions do not have names.)

https://docs.swift.org/swift-book/LanguageGuide/Extensions.html

Upvotes: 2

Related Questions