attribute

  • Store properties (either constants (let) or variables (var) store properties)
1  class LGTeacher{
2 	let age: Int = 18
3 	var name: String = "Kody"
4  }
5  let t = LGTeacher()
Copy the code

In the case of age and name above, these are our variable store attributes, which we can also see in SIL:

  • Compute attributes (As the name implies, compute attributes do not take up storage space and are essentially GET /set methods)
  • Attribute observer :(willSet,didSet)

Delayed storage property

1 class LGTeacher{
2 	lazy var age: Int = 10 
3 }
Copy the code
  • A storage property decorated with lazy
  • The deferred storage property must have a default initial value
  • Deferred storage is assigned only on the first access
  • Delayed storage of properties does not guarantee thread-safety
  • The effect of deferred storage properties on the size of an instance object

The type attribute

1  class LGTeacher{
2      static var age: Int = 10 
3  }
Copy the code
  • Use the keyword static
  • The type attribute must have a default initial value
  • Type attributes are initialized only once

The correct way to write a singleton

1 class LGTeacher{
2 	static let sharedInstance: LGTeacher = LGTeacher() 
3 	private init(){}
4 }
Copy the code
  • Use static let to create and declare an instance object
  • Add access control permission private to the current init

Initialization of the structure

  • Structure does not require a custom initialization method. Compare the following two pieces of code
1 //1
2  struct LGTeacher{
3 	var age: Int
4	var name: String
5  }
6
7 //2
8  class LGStudent{
9	var age: Int
10 	var name: String
11  }
Copy the code

Class ‘LGStudent’ has no initializers. This is because the compiler automatically helps us compose initializers in the structure, which means we can call them like this:

It can also be viewed through SIL :(if you don’t know what SIL is, you can search for it yourself)

  • If our property has a default initialization value, the system provides a different default initialization method

  • If we customize the initialization method, the system will not generate the initialization method for us