Object-C ---) Swift (9) Delayed Storage attributes
Swift introduces a new mechanism-delay storage attribute mechanism, which is used to calculate the attribute of the initial value when it is called for the first time. lazy modifier is required for declaration.
Note: When defining an attribute, it must be a variable (var). constants cannot use the delay storage mechanism.
When is latency storage used?
When an instance holds a reference for another instance with a high creation cost, using Delayed Storage can reduce memory overhead and improve performance.
Class Bird {var name: String var age: Int init (age: Int) {self. name = "" NSThread. sleepForTimeInterval (2) self. age = age} class Ostrich {var name: String = "" var age = Bird (age: 3)} var ostrich = Ostrich () ostrich. name = "ostrich" print (ostrich. name)
Running the above Code, we obviously found that it took two seconds to print out the code. The Ostrich obviously didn't care about the age attribute of Ostrich at all, so there is no need to wait for the two seconds, so we can consider changing it in the code.
Lazy var age = Bird (age: 3)
In this way, no Bird instance will be created without calling age, thus improving the performance. There is no waiting delay of two seconds.