Introduction to Lazy Loading lazy loading
- Lazy loading is also the way of Swift
- (Apple's design idea: that all objects are actually loaded into memory when they are used)
- Unlike OC, Swift has a special keyword to implement lazy loading
- The Lazy keyword can be used to define an attribute lazy loading
Lazy-Loading use
var 变量: 类型 = { 创建变量代码 }()
// 懒加载的本质是,在第一次使用的时候执行闭包,将闭包的返回值赋值给属性 // lazy的作用是只会赋值一次 lazy var array : [String] = { () -> [String] in return ["why", "lmj", "lnj"] }()
Import UIKitclassViewcontroller:uiviewcontroller {lazy var names: [String]={print ("------") return[" Why","YZ","LMJ"] }() Overridefunc viewdidload () {super.viewdidload ()}OverrideFunc Touchesbegan (_ Touches:set<uitouch>, withEvent: Uievent?) { _ =Names.count _=Names.count _=Names.count _=Names.count _=Names.count _=Names.count}}
Import UIKitclassViewcontroller:uiviewcontroller {//mark:-Lazy-loaded Properties ///properties of the TableViewLazy var Tableview:uitableview =UITableView ()//mark:-System callback function Overridefunc viewdidload () {super.viewdidload () Setupui ()}}//mark:-setting UI interface relatedextension Viewcontroller {///setting the UI interfacefunc setupui () {//0. Add TableView to the view of the controllerView.addsubview (TableView)//1. Set the frame of the TableViewTableview.frame =View.bounds//2. Setting up a data sourceTableview.datasource = Self//3. Setting up the agentTableView.Delegate=Self }}//mark:-tableview Data Sources and Proxy methods: 1: Set proxy for multiple proxies, separated by 2: equivalent to OC's #pragma://mark:-2: If there is no preposition, it is underlined to say: _ TableView//extension similar to OC category, also can only expand the method, cannot expand the propertyextension Viewcontroller:uitableviewdatasource, uitableviewdelegate{func TableView (_ Tableview:uitableview, num Berofrowsinsection section:int)-Int {return -} func TableView (_ Tableview:uitableview, Cellforrowat Indexpath:indexpath)-UITableViewCell {//1. Create a cell:Let Cellid ="Cellid"var cell=Tableview.dequeuereusablecell (withidentifier:cellid)ifCell = =Nil {//use enumerations in Swift: 1> enumeration types. Specific type 2>. Specific typeCell = UITableViewCell (style:.default, Reuseidentifier:cellid)} //2. Set the data to the cell: The cell is an optional type, the cell removed from the cache pool can be empty, so the optional type, the last time to return to the cell to be forced to unpack, it is guaranteed that the optional type is not empty, if the empty forced unpacking will be emptyCell?. Textlabel?. Text ="test data: \ ((Indexpath as Nsindexpath). Row)" //3. Return to cell returncell!} func TableView (_ Tableview:uitableview, Didselectrowat indexpath:indexpath) {print ("clicked: \ ((Indexpath as Nsindexpath). Row)") }}
Swift Learning Day 16th: Lazy Loading and TableView