Sunkas
Sunkas

Reputation: 9590

Resuse instance constant in swift

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.

Upvotes: 0

Views: 53

Answers (2)

Sajjon
Sajjon

Reputation: 9907

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 }

Upvotes: 1

Chris Conover
Chris Conover

Reputation: 9039

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.

Upvotes: 0

Related Questions