Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift constant that depends on another constant

I'm attempting to create a constant that depends on another in the following way:

class Thingy {
 let paddingConstant = 13.0
 let paddingDict = ["padding": paddingConstant]
}

The bottom line gives me an error "Thingy.Type does not have a member named 'paddingConstant'".

Is it possible to declare a constant that depends on another?

like image 316
Julian B. Avatar asked Dec 01 '22 00:12

Julian B.


2 Answers

Another solution is to declare this variable lazy. The advantage is that, unlike a calculated property, it does not perform the calculation every time you fetch its value; but the downside is that it cannot be a constant, unfortunately:

class Thingy {
    let paddingConstant = 13.0
    lazy var paddingDict : [String:Double] = 
        ["padding": self.paddingConstant]
}

I regard that limitation as a bug in the Swift language.

like image 175
matt Avatar answered Dec 10 '22 14:12

matt


You can move paddingDict to the init:

class Thingy {
    let paddingConstant = 13.0
    let paddingDict : [String: Double]
    init() {
        paddingDict = ["padding": paddingConstant]
    }
}
like image 21
Tim Avatar answered Dec 10 '22 14:12

Tim