Adding function parameter to view results in error for existing computed property

I'm trying to pass a function into my view, which also has a calculated property as an init value. Previously, the following code worked fine before attempting to add the function as an init property of my view:

var title: String
var desc: String {
    get {
        return self._desc
    }
    set {
        self._desc = newValue
        self.suggestions = newValue.components(separatedBy: "\n\n")
    }
}

private var _desc: String = ""
private var suggestions:[String] = []

public init(title: String, desc: String) {
    self.title = title
    self.desc = desc
}

No Errors—everything works as expected. But then when I add my function to the view and in the init, suddenly it is erroring on the previous line, as if my computed property was the problem:

var title: String
var desc: String {
    get {
        return self._desc
    }
    set {
        self._desc = newValue
        self.suggestions = newValue.components(separatedBy: "\n\n")
    }
}
var action: () -> Void
private var _desc: String = ""
private var suggestions:[String] = []

public init(title: String, desc: String, action: @escaping () -> Void) {
    self.title = title
    self.desc = desc // Errors here: "'self' used before all stored properties are initialized"
    self.action = action
}

I've looked at all the posts I can find with this error, but they all deal with circumstances unrelated to what I'm seeing here.

Does anyone understand what is happening? Why would adding another parameter to a view trigger this error for a computed property when otherwise it worked fine?

Replies

So it appears the problem it had was with the order of the parameters, because the following builds without error: `var action: () -> Void

    var title: String

    var desc: String {

        get {

            return self._desc

        }

        set {

            self._desc = newValue

            self.suggestions = newValue.components(separatedBy: "\n\n")

        }

    }

    private var _desc: String = ""

    

    private var suggestions:[String] = []

    

    public init(action: @escaping () -> Void, title: String, desc: String) {

        self.action = action

        self.title = title

        self.desc = desc

    }`

Also worth mentioning is that the type of value being added as a parameter didn't matter (I tried it as a string and it was the same as when it was a function).

If anyone can explain what is going on here—I'd very much appreciate it. If you happen to run into this problem, try rearranging the order of your parameters.

The reason should be:

  • when you call desc (computed value), you use self.
  • But self was not completely initialized then (action not set).
  • when you change order, you initialize all stored properties, now you can call desc (which uses self.)

Could you post the complete class code so that we can test ?