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