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?

+3


source to share


5 answers


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]
}

      

+1


source


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.

+6


source


You can move paddingDict to init:

class Thingy {
    let paddingConstant = 13.0
    let paddingDict : [String: Double]
    init() {
        paddingDict = ["padding": paddingConstant]
    }
}

      

+5


source


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.

+2


source


Yes, it is possible. You need to make paddingDict read-only computed property

class Thingy {

    let paddingConstant = 13.0

    var paddingDict : [String : Double] {

        get {return ["padding": paddingConstant] }
    }
}

      

0


source







All Articles