abdel
abdel

Reputation: 125

Swift Struct with static values

I use this struct :

struct Constants {
  struct array {
     static let fuel = [NSLocalizedString("Gasoline", comment: ""),
                           NSLocalizedString("Diesel", comment: ""),
                           NSLocalizedString("Hybrid", comment: ""),
                           NSLocalizedString("Electric", comment: ""),
                           NSLocalizedString("other", comment: "")]
  }
}

I do the call Constants.array.fuel in other place, it's work fine. the problem is when I change the app language, the NSLocalizedString not working as expected (I get the old translate). probably because I use static. in other viewcontrollers, NSLocalizedString works fine. when I remove static, I get :

Instance member 'fuel' cannot be used on type 'Constants.array'

any help please.

Upvotes: 1

Views: 2041

Answers (1)

Maxim Kosov
Maxim Kosov

Reputation: 1980

The problem is fuel property is a constant. Its initialized only once and then won't change during whole application lifetime.

You may make it calculated property by replacing static let with static var fuel: [NSLocalizedString] { return [NSLocalizedString("Gasoline", comment: ""), ...] }

This way, property will be calculated each time you access it. Of course, it won't work as fast as with constant.

Upvotes: 4

Related Questions