Search code examples
swiftclassinitializationlazy-evaluationlazy-initialization

Set lazy var from outside without initializing


I defined a class using a lazy var definition, where EXIFData is a struct:

struct EXIFData {
    var a : String
    var b : String
}

class xxx {
...
    lazy var exif: EXIFData = {
    ...
        return EXIFData(url: self.initUrl as CFURL)
    }()

Now I want to assign a value to some members without executing the initial code of lazy var definition. How can I avoid it and assing an own created struct member instead like c.exif.a = newExif.a ? I'm using Swift 3.0.

Added: I solved it this way: As part from the same class I use the needed information to assign my value within the lazy initialization. So there is only one additional "if" statement within. No need for external excess and special tricks to avoid standard initialization.


Solution

  • The lazy initializer won't run if you just assign a value normally before ever reading. Here's a test case:

    class Class {
        lazy var lazyVar: String = {
            print("Lazy initializer ran")
            return "Default value"
        }()
    }
    
    let object = Class()
    object.lazyVar = "Custom value"
    print(object.lazyVar)