简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM