The lazy on Swift

Source: Internet
Author: User

Lazy as the name implies is slow, million must not move.

The same is true of a variable, which is only loaded when you first use it. All also known as lazy loading, is required to load.

=========

The benefits of doing this:

1. Modularization, the code of the object is written in the Get method, the code is more readable.

2. Small footprint "In some cases, this object must not necessarily be created", load on Demand

=======

How is it manifested?

1.OC:

-(UITableView *) tableview{

if (! _tableview) {

_tableview = [[UITableView alloc] init];

}

return _tableview;

}//will only be created when the Self.tableview is first called _tableview

2.swift:

2.1 Simple expressions: lazy var dataarr = Array<Product> ()

2.2 closures: lazy var titlestr:string = {return ' title '} ()

============

Examples of Use:

1. Requires further processing of attributes to be used

Class Lazydemo {

var url:String

lazy var requesturl:String = {

[unowned self] in

if self . URL. Hasprefix("/http") {

return self . URL

}Else{

return "http://". Stringbyappendingstring(self. URL)

}

}()

init(url:String) {

self. URL = URL

}

}

2. Complex calculations are required

Lazy var second: Int = {

var sum = 0

for i in 1.. . 100000{

sum + = i

}

return sum

}()

3. Properties are not determined whether they will be used: example source

Class dataimporter {

/*

    dataimporter is a Class to import data from an external file

The class is assumed to take a non-trivial Amount of time to initialize.

*/

var fileName = "Data.txt"

//The Dataimporter class would provide data importing Functionality here

}

class DataManager {

Lazy var importer = Dataimporter ()

var data = [String] ()

//The DataManager class would provide data Management Functionality here

}

let manager = DataManager ()

Manager.data.append ("Some data")//This time only initializes importer

Manager.data.append ("Some more Data")

The lazy on Swift

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.