Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can one set a "computed constant" in a Swift `struct`?

Tags:

swift

For convenience in naming constants I would like to do the following in Swift (my real case is less trivial) so I could refer to IntegerConstants.SIX in later code. However, SIX cannot be given a value because ONE and TWO do not have values till the struct has been initialized .. bit of a "Catch-22"

struct IntegerConstants {
   let ONE = 1.0
   let TWO = 2.0
   let SIX = (ONE + TWO) * TWO
}

Is there a way to do this, or an equivalent that creates a named constant of the form "GROUP.VALUE", that I have not yet discovered?

like image 471
Ramsay Consulting Avatar asked May 24 '17 22:05

Ramsay Consulting


1 Answers

If you're using this to group constants, as with IntegerConstants.six, what you actually want to do is make them static. This also solves your error since you don't need to access a self.

struct IntegerConstants {
    static let one = 1
    static let two = 2
    static let six = (one + two) * two
}
like image 105
John Montgomery Avatar answered Jan 04 '23 01:01

John Montgomery