带静态值的Swift结构
我使用这个结构:带静态值的Swift结构,swift,struct,Swift,Struct,我使用这个结构: struct Constants { struct array { static let fuel = [NSLocalizedString("Gasoline", comment: ""), NSLocalizedString("Diesel", comment: ""), NSLocalizedString("Hybrid", comment: ""),
struct Constants {
struct array {
static let fuel = [NSLocalizedString("Gasoline", comment: ""),
NSLocalizedString("Diesel", comment: ""),
NSLocalizedString("Hybrid", comment: ""),
NSLocalizedString("Electric", comment: ""),
NSLocalizedString("other", comment: "")]
}
}
我在其他地方调用Constants.array.fuel
,工作正常。
问题是当我更改应用程序语言时,NSLocalizedString
无法按预期工作(我得到了旧的翻译)。
可能是因为我使用了static
。在其他ViewController中,NSLocalizedString
工作正常。
当我删除static
时,我得到:
Instance member 'fuel' cannot be used on type 'Constants.array'
请提供帮助。问题是
燃油属性是常量。它只初始化一次,然后在整个应用程序生命周期内不会更改
您可以将静态let
替换为
静态var燃料:[NSLocalizedString]{返回[NSLocalizedString(“汽油”,注释:),…])
这样,每次访问属性时都会计算该属性。当然,它的工作速度不如常数快。问题在于燃料属性是常数。它只初始化一次,然后在整个应用程序生命周期内不会更改
您可以将静态let
替换为
静态var燃料:[NSLocalizedString]{返回[NSLocalizedString(“汽油”,注释:),…])
这样,每次访问属性时都会计算该属性。当然,它的运行速度不如常量。正如您所说,它的运行速度不如常量。例如,是否有其他方法重置结构?否则我会接受你的回答。谢谢you@abdel您可以将私有可选属性设置为nil
。然后将属性设置为计算属性,如果私有属性为nil
,则将其设置为数组,然后返回已展开的私有属性。当您更改语言时,只需再次将私有属性设置为nil
,以强制在下次使用时重新计算它。正如您所说,它的工作速度不如常量快。例如,是否有其他方法重置结构?否则我会接受你的回答。谢谢you@abdel您可以将私有可选属性设置为nil
。然后将属性设置为计算属性,如果私有属性为nil
,则将其设置为数组,然后返回已展开的私有属性。更改语言时,只需再次将私有属性设置为nil
,以强制在下次使用时重新计算它。