Lazy Loading
Lazy loading is ubiquitous in IOS development
- Lazy loading format is as follows:
var person: Person = { print("懒加载") return Person()}()
- Lazy loading is essentially a closed package
- The above code can be rewritten in the following format
let personFunc = { () -> Person in print("懒加载") return Person()}lazy var demoPerson: Person = self.personFunc()
- A simple notation for lazy loading
var demoPerson: Person = Person()
Read-only property getter & Setter
getter & setter
rarely used in Swift, the following code is for information only
var _name: String?var name: String? { get { return _name } set { _name = newValue }}
Storage-Type Properties & computed properties
- Storage-type properties-need to open up space to store data
- Computed properties-Execution functions return other memory addresses
var title: String { get { return "Mr " + (name ?? "") }}
- A property that implements only getter methods is called a computed property, equivalent to the ReadOnly attribute in OC
- Computed properties themselves do not occupy memory space
- You cannot set a value for a computed property
- Computed properties can use the following code shorthand
var title: String { return "Mr " + (name ?? "")}
Comparison of computed properties with lazy loading
- Computed properties
- Do not allocate independent storage space to save calculation results
- Executed each time it is called
- More like a function, but cannot receive parameters, and must have a return value
var title2: String { return "Mr" + (name ?? "")}
- Lazy Load Properties
- When the first call is performed, the closure is executed and the value returned by the space storage closure is allocated
- Separate storage space is allocated
- Unlike OC, the Lazy property is not called again even if it is set to nil
var title: String = { return "Mr " + (self.name ?? "")}()
Introduction to Swift lazy loading and read-only properties