Fast constant depending on another constant
I am trying to create a constant that depends on another, like this:
class Thingy {
let paddingConstant = 13.0
let paddingDict = ["padding": paddingConstant]
}
The bottom line is giving me an error "Thingy.Type does not have a member named 'paddingConstant'"
.
Is it possible to declare a constant that depends on another?
source to share
As another solution, you can use an external structure to define a constant (and any other constants you may need):
struct Constants {
static let paddingConstant = 13.0
}
and then use it in the class Thingy
:
class Thingy {
let paddingDict = ["padding": Constants.paddingConstant]
}
source to share
Another solution is to declare this variable lazy
. The advantage is that, unlike a computed property, it does not perform a computation every time you retrieve its value; but the disadvantage is that it cannot be persistent, unfortunately:
class Thingy {
let paddingConstant = 13.0
lazy var paddingDict : [String:Double] =
["padding": self.paddingConstant]
}
I regard this limitation as a bug in Swift language.
source to share
You can fill instance constant property a
(at definition time) using the value of another constant property b
if b
defined static
.
class Thingy {
static let paddingConstant = 13.0
let paddingDict = ["padding": paddingConstant]
}
This is a direct response to the error message I received:
Thingy.Type has no member named "paddingConstant"
Infact, by creating paddingConstant
static it will become Type property
: part Thingy.Type
.
Hope it helps.
source to share