Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

The common way to write class

//****** ****** ******* class CJLTeacher {var age: Int = 18 func teach(){print("teach")} init(_ age: Int) {self.age = age}} var t = cjlteacher.init (20) //****** 下 一 ******* class CJLTeacher {var age: Int? func teach(){ print("teach") } init(_ age: Int) { self.age = age } } var t = CJLTeacher.init(20)Copy the code

In a class, if the attribute is not assigned and is not optional, the compilation will report an error

Why are classes reference types?

Define a class, illustrated by an example

class CJLTeacher1 {
    var age: Int = 18
    var age2: Int = 20
}
var t1 = CJLTeacher1()
Copy the code

Class initialization object T1, stored in the global section

  • Print T1, T:po t1As can be seen from the picture,t1What’s in memory space isaddressAnd what t stores isvalue

Gets the address of the T1 variable and looks at its memory

  • To obtaint1Pointer address:po withUnsafePointer(to: &t1){print($0)}
  • T1 global address memory:x/8g 0x0000000100008218
  • The heap address memory stored in t1:x/8g 0x00000001040088f0

Reference type characteristics

  • 1. What is stored in the addressThe heap area address
  • 2,The heap area addressIs stored invalue

Question 1: If t1 is assigned to T2, will t1 be changed if T2 is changed?

  • throughlldbDebugging learned, modifiedt2Will,Cause t1 to changeMainly becauset2,t1All of the addresses are storedSame heap area address, if modified, the same heap address is changed, so changing T2 will cause T1 to be changed together, that isShallow copy

Question 2: If the structure contains class objects, will t change if the instance object properties in T1 are modified?

The code is shown below

class CJLTeacher1 { var age: Int = 18 var age2: Int = 20 } struct CJLTeacher { var age: Int = 18 var age2: Int = 20 var teacher: CJLTeacher1 = CJLTeacher1()} var t = CJLTeacher() var t1 = t t1.teacher.age = 30 // Print teacher.age in t1 and t respectively. The result is as follows t1.teacher.age = 30 t.teacher.age = 30Copy the code

As can be seen from the printed result, if the attributes of the instance object in T1 are modified, the attributes of the instance object in T will change. Although the value is passed in the structure, the address is still passed in the teacher because it is a reference type

This can also be verified by LLDB debugging

  • Print the address of T:po withUnsafePointer(to: &t){print($0)}
  • Print the memory of t:x/8g 0x0000000100008238
  • Print the memory situation of teacher address in T:x/8g 0x000000010070e4a0

Pay attention to: When writing code, you should try your bestAvoid value types containing reference types