Object-C ---) Swift (9) Delayed Storage attributes

Source: Internet
Author: User

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.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.