1

So, in objective C, and C/C++, and .NET, and pretty much all other languages I've used, you can declare constants that can include previous constants, like

#define PI 3.14159
#define HALFPI (PI/2)

const CGFloat BOTTOM_BAR_HEIGHT = 200;
const CGFloat BOTTOMBARCONTENTS_DY = BOTTOM_BAR_HEIGHT/2;

But this doesn't seem to work in swift

let PI=3.14159
let HALF_PI=PI/2

This is a really useful pattern if you're trying to do things like (one among many examples) layout dimensions, or really any set of constants that are interdependent. Is there any way to achieve this pattern in swift, without declaring them as vars and setting them in an initializer function (which will double the size and reduce maintainability of some really lengthy code, incur whatever low-level penalties for using vars instead of lets, and ruin my first impression of swift)? Thanks.

Chris
  • 629
  • 1
  • 10
  • 28
  • Define "doesn't seem to work". – rmaddy Apr 09 '18 at 00:36
  • 4
    FYI - Do not define your own `PI`. Use `Double.pi` or `CGFloat.pi` where needed. – rmaddy Apr 09 '18 at 00:37
  • 3
    If these constants are being defined in a class, make them `static`. – rmaddy Apr 09 '18 at 00:48
  • Oops, rmaddy I should clarify that I'm trying to do this outside of a function in the class body. It seems to work in a function body. Which would be fine if I only needed them in one function. So I'm getting the compile error "cannot use instance member XYZ in intializer". (And PI is an example of course) – Chris Apr 09 '18 at 00:49
  • Boom that worked. (using static). Thanks!! – Chris Apr 09 '18 at 00:51
  • "instance member" should have been the clue I guess. Thanks again. I can't mark your response as the answer... what's the right way to close this out? – Chris Apr 09 '18 at 00:53
  • Check [this thread](https://stackoverflow.com/q/25854300/6541007) or [this](https://stackoverflow.com/q/45423321/6541007) or many other threads which you can find searching with the error message. This question should be marked as duplicate. – OOPer Apr 09 '18 at 01:58
  • The two you've linked, honestly, have the same error message but are different problems and solutions. They apply to vars and the solution is not to make them static. Making "let"s static is the perfect solution to my problem, is analogous to class consts in C++. – Chris Apr 09 '18 at 02:23
  • For this case maybe using `lazy var HALF_PI` will work – CZ54 Apr 09 '18 at 09:01

1 Answers1

0

Possibly You can use a NSObject Class like This:

import UIKit
class ViewController: NSObject {  
    static let PI = 3.14
    static let HALF_PI = ViewController.PI/2 
}

To achieve this you can Use Static

And use it to any View controller like

 print(ViewController.PI)
 print(ViewController.HALF_PI)

Hope this Helps.

Abhirajsinh Thakore
  • 1,806
  • 2
  • 13
  • 23