-1

No idea why this error occurred, and I suspect that it's just me putting initialization in the wrong place. I've checked this post but didn't help. I can't figure out why.


struct TodosDocument: FileDocument {
    ...
    var defaultText: String = defaultContent
    var content: String
    ...
    init(content: String = defaultContent, defaultText: String = defaultContent) {
        self.defaultText = defaultText
        self.content = content
        do {
            self.todo = try JSONDecoder().decode(Context.self, from: content.data(using: .utf8)!)
        } catch {
            print("ERROR \(error)")
            fatalError()
        }
    }

    
    static var readableContentTypes: [UTType] { [.TodoType] }

    init(configuration: ReadConfiguration) throws {
        guard let data = configuration.file.regularFileContents,
              let string = String(data: data, encoding: .utf8)
        else {
            throw CocoaError(.fileReadCorruptFile)
        }
        self.content = string
        do {
            self.todo = try JSONDecoder().decode(Context.self, from: data)
        } catch {
            self.todo = try JSONDecoder().decode(Context.self, from: defaultText.data(using: .utf8)!) // <- here
        }
    }
    ...
Dan Morrow
  • 4,433
  • 2
  • 31
  • 45
  • You just cant user `defaultText` for assignment inside init. Bcz The compiler in Swift works like you should not use self objects/properties in right side of assignment operand inside init. – Kudos May 30 '22 at 07:12
  • 1
    Move the decoding stuff out of the init methods, they are causing the errors and also that kind of code doesn't really belong in an init – Joakim Danielson May 30 '22 at 07:12

1 Answers1

0

I am taking a gander here in assuming that XCode is complaining over the fact that self.todo = try JSONDecoder().decode(Context.self, from: defaultText.data(using: .utf8)!) is not a static var.

So maybe check out this post for more info: https://stackoverflow.com/a/64207731/9714666 (this one explains it best rather than your linked one :))

Gideon Botha
  • 126
  • 10