iOS Swift4 - 重新初始化惰性变量
iOS Swift4 - reInitialize lazy variable
有没有办法根据当前语言重新初始化惰性变量?
lazy var localizableDictionary: NSDictionary! = {
guard let path = Bundle.main.path(
forResource: "Localizable",
ofType: "strings",
inDirectory: nil,
forLocalization: Localizer.shared.currentLanguage)
else {
fatalError("Localizable file NOT found")
}
return NSDictionary(contentsOfFile: path)
}()
它是一个 lazy var
显然它是一个变量,因此 Swift 不会阻止您在必要时随时修改它的值。
你可以随时说,
guard let path = Bundle.main.path(
forResource: "Localizable",
ofType: "strings",
inDirectory: nil,
forLocalization: Localizer.shared.currentLanguage)
else {
fatalError("Localizable file NOT found")
}
self.localizableDictionary = NSDictionary(contentsOfFile: path)
仅供参考
Lazy initialization (also sometimes called lazy instantiation, or lazy
loading) is a technique for delaying the creation of an object or some
other expensive process until it’s needed. When programming for iOS,
this is helpful to make sure you utilize only the memory you need when
you need it.
以上引用自 http://mikebuss.com/2014/06/22/lazy-initialization-swift/
请不要以为惰性变量是常量,如果您真的需要一个常量,您会立即选择 let :)
希望对您有所帮助
有没有办法根据当前语言重新初始化惰性变量?
lazy var localizableDictionary: NSDictionary! = {
guard let path = Bundle.main.path(
forResource: "Localizable",
ofType: "strings",
inDirectory: nil,
forLocalization: Localizer.shared.currentLanguage)
else {
fatalError("Localizable file NOT found")
}
return NSDictionary(contentsOfFile: path)
}()
它是一个 lazy var
显然它是一个变量,因此 Swift 不会阻止您在必要时随时修改它的值。
你可以随时说,
guard let path = Bundle.main.path(
forResource: "Localizable",
ofType: "strings",
inDirectory: nil,
forLocalization: Localizer.shared.currentLanguage)
else {
fatalError("Localizable file NOT found")
}
self.localizableDictionary = NSDictionary(contentsOfFile: path)
仅供参考
Lazy initialization (also sometimes called lazy instantiation, or lazy loading) is a technique for delaying the creation of an object or some other expensive process until it’s needed. When programming for iOS, this is helpful to make sure you utilize only the memory you need when you need it.
以上引用自 http://mikebuss.com/2014/06/22/lazy-initialization-swift/
请不要以为惰性变量是常量,如果您真的需要一个常量,您会立即选择 let :)
希望对您有所帮助