0

I'm trying to create a variable of type Dictionary<String, Double> where one of the value in the dictionary is calculated from an instance variable of the type.

class CalculatorBrain {
    private var accumulator = 0.0

    private var operations: Dictionary<String, Double> = [
        "π": M_PI,
        "√": sqrt(accumulator)
    ]
}

enter image description here

But I have encountered the following error.

Cannot use instance member 'accumulator' within property initializer; property initializers run before 'self' is available

I thought maybe this has something to do with how Swift initialisation order works, so I added keyword lazy to the dictionary variable, so that it will only be initialised when it is used. However, this doesn't work as well.

Why does the error occur and how to make it work?

class CalculatorBrain {
    private var accumulator = 0.0

    lazy private var operations: Dictionary<String, Double> = [
        "π": M_PI,
        "√": sqrt(accumulator)
    ]
}

enter image description here

halfer
  • 19,824
  • 17
  • 99
  • 186
Thor
  • 9,638
  • 15
  • 62
  • 137
  • sorry, will do so now – Thor Mar 14 '17 at 08:22
  • Possible duplicate of http://stackoverflow.com/questions/25854300/how-to-initialize-properties-that-depend-on-each-other – Note that you have to reference the other property via explicit "self": `sqrt(self.accumulator)`. – Martin R Mar 14 '17 at 08:24
  • Or this one: http://stackoverflow.com/questions/39867568/initialize-lazy-instance-variable-with-value-that-depends-on-other-instance-vari. – Martin R Mar 14 '17 at 08:25
  • But note that the accumulator is evaluated when the operations dictionary is created, not when the square root value is retrieved. That might not be what you really want. – Martin R Mar 14 '17 at 08:53
  • oh ok, if accumulator is evaluated when the operations dictionary is created, then does it mean that "sqrt(accumulator)" will always equal to 0? – Thor Mar 14 '17 at 09:15
  • Sorry if my question is not very specific or correct, but I'm not exactly sure what you last comment really meant. Could you please expand on it a bit more, if possible? – Thor Mar 14 '17 at 09:22

1 Answers1

1

You should indicate that dictionary has no value at init time but will have a value after that.

In Swift all variables must be initialized or marked as Optional.

public class CalculatorBrain {
    private var accumulator: Double = 0.0

    lazy private var operations: [String: Double] = self.loadDictionary()



    private func loadDictionary() -> [String: Double]
    {
        var operations: [String: Double] = [
            "π": M_PI,
            "√": sqrt(accumulator)
        ]

        return operations
    }
}
Adolfo
  • 1,862
  • 13
  • 19