Why does my @lazy property crash, but if I make it non lazy it works?

后端 未结 1 1425
遥遥无期
遥遥无期 2021-01-13 14:49

I have a problem with lazy properties. I thought I got them but maybe I didn\'t / maybe it is a bug

I have a lazy array in my class

@lazy var entered         


        
1条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-13 15:25

    After some trial, I found something quite odd.

    First of all, if we wrap the var inside a class, it simply works:

    class RegionManager {
        @lazy var enteredRegions = Array()
    }
    

    In AppDelegate, I declared a @lazy var regManager = RegionManager().

    Then, in application:didFinishLaunching:, I modify and use the value, it works without spitting a word:

    regManager.enteredRegions.append("New!")
    println("Regions: \(regManager.enteredRegions)") // Regions: [New!]
    

    After this, I tried to change to some native values, for example, String, Int and so on, they all fail.

    So, my guess is that this strange behaviour is actually a bug of the compiler itself, it may be rooted in some optimization for native types, maybe there's a inner pool or what that apple doesn't tell us.

    0 讨论(0)
提交回复
热议问题