0

I am trying to set an instance constant/variable set in Swift an directly reuse it to set another instance constant/variable

This code does not work:

let stLoginViewYDeltaWhenKeyboardIsShowing = DEVICE_HAS_IPHONE4_SCREEN_SIZE ? 0.0 : -16.0
let loginViewYDeltaWhenKeyboardIsShowing = IS_ST_TARGET ? stLoginViewYDeltaWhenKeyboardIsShowing : 30.0

It gives an error:

'LoginViewController.Type' does not have a member named 'stLoginViewYDeltaWhenKeyboardIsShowing'

This code does compile but does not look that good:

static let stLoginViewYDeltaWhenKeyboardIsShowing = DEVICE_HAS_IPHONE4_SCREEN_SIZE ? 0.0 : -16.0
let loginViewYDeltaWhenKeyboardIsShowing = IS_ST_TARGET ? LoginViewController.stLoginViewYDeltaWhenKeyboardIsShowing : 30.0

Any better approaches? In Objective-C both #define and a normal variable would have worked.

Sunkas
  • 9,542
  • 6
  • 62
  • 102

2 Answers2

1

You can do it this way:

class var myConstant: String  { return "my constant" }

Since it is a computed property you cannot "write over" its value, thus its value is constant. I think it is more neat than using "static let"

So for your case:

class var stLoginViewYDeltaWhenKeyboardIsShowing: CGFloat { 
    return DEVICE_HAS_IPHONE4_SCREEN_SIZE ? 0.0 : -16.0
}

EDIT: Thanks @ABakerSmith for pointing out that you don't need to write get { return }

Sajjon
  • 8,938
  • 5
  • 60
  • 94
0

Using static is the best way, it is clean, and makes the most sense. If you want a const, then use let as you have been doing. You can use a much shorter name though, since the context is bound do your view controller (it is pretty obvious what it is for).

But since you are asking, for your needs, there is a much better solution. Use auto layout constraints and avoid hardcoding constants like these in. I have ripped out logic like this from two projects, and it is a hassle. Keyboard stuff is tricky though, you just have to find the simplest general solution that you can understand, and then use constraints.

Chris Conover
  • 8,889
  • 5
  • 52
  • 68
  • ı would disagree that my solution with static is clean. I am using auto-layout constraints. The constants are for constraint offsets. But a much better solution would of course be to make them dependent on the screen in all scenarios to avoid the constants. The naming can of coarse be shortened, but in this case I find it good as there are more views in `LoginViewController` than the loginView. – Sunkas Jun 08 '15 at 09:16