Anas Alhasani
Anas Alhasani

Reputation: 97

iOS Swift4 - reInitialize lazy variable

Is there a way to reInitialize lazy variable based on the current language ?

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)
}()

Upvotes: 1

Views: 519

Answers (1)

Sandeep Bhandari
Sandeep Bhandari

Reputation: 20369

its a lazy var clearly its a variable, so Swift will not stop you from modifying its value at any point in time if thats necessary.

You can simply say at any point,

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)

FYI

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.

above quote copied from http://mikebuss.com/2014/06/22/lazy-initialization-swift/

Please don't be under the impression that lazy var are constants if you really need a constant you will opt for let straight away :)

Hope it helps

Upvotes: 2

Related Questions