0

I don't understand why this is not allowed in Swift:

let graphPointCircleDiameter: CGFloat = 5.0
let graphPointCircleDisplacement: CGFloat = graphPointCircleDiameter/2

I get the error:

Instance member 'graphPointCircleDiameter' cannot be used on type NameOfVC.

Can anyone explain why a static "let" variable cannot be referenced by another variable on the global scope in Swift?

Thank you!

Scriptable
  • 19,402
  • 5
  • 56
  • 72
jacquelion
  • 149
  • 5
  • I think you're going to want to include more of your code. The code you provided works just fine in a playground (I just checked). The error message indicating that this is an instance member implies there's at least a class definition involved... – Mark Bessey Jun 07 '16 at 22:04
  • you need a computed property `var graphPointCircleDisplacement: CGFloat { return graphPointCircleDiameter/2 }` – Leo Dabus Jun 07 '16 at 23:32

1 Answers1

0

let defines a constant, while var defines a variable. If you want to assign a variable from a global constant then you can set graphPointCircleDisplacement as a lazy var instead:

let graphPointCircleDiameter: CGFloat = 5.0
lazy var graphPointCircleDisplacement: CGFloat = self.graphPointCircleDiameter/2

As Leo Dabus mentioned, you can also return the value of the constant to define another:

var graphPointCircleDisplacement: CGFloat { return graphPointCircleDiameter/2 }
Community
  • 1
  • 1
l'L'l
  • 44,951
  • 10
  • 95
  • 146
  • Can you explain why a computed property is needed or why a lazy var property is needed? To me it seems like it should be possible to use global variables that are constants in the definition of other global variables, like in JavaScript. Does this have to do with when global variables are initialized in Swift? – jacquelion Jun 08 '16 at 23:06