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

Let’s use an example to introduce what is a value type

Func test(){// The stack declares an address, Print ("age=(age),age2=(age2)")} test()Copy the code

As you can see from the example, age is stored on the stack

  • Looking at the memory of age, you can see that the stack area stores values directly

    • Get stack address of age:po withUnsafePointer(to: &age){print($0)}
    • Age memory:x/8g 0x00007ffeefbff3e0

  • To viewage2As can be seen from the graph below,age2The assignment ofageTake the value of, and assign it toage2. Among themage 与 age2The address of the8Bytes, from which we can tell that the stack space iscontinuous, and isFrom high to lowthe

So, age is the value type

Value type characteristics

  • 1. What is stored in the addressvalue
  • 2. During the transfer of value types, equivalent topassaA copy of theThat’s what’s calledDeep copy
  • 3. State is not shared during value transfer

The structure of the body

The usual way of writing a structure

Struct CJLTeacher {var age: Int = 18 func teach(){print("teach")}} var t = CJLTeacher() ***** Int func teach(){ print("teach") } } var t = CJLTeacher(age: 18)Copy the code
  • In structs, compilation does not report errors if you do not give default values to attributes. That is, a property may or may not be assigned in a structure
  • initMethods can be overridden, or they can use the system default

Why are structs value types?

Define a structure and analyze it

struct CJLTeacher {
    var age: Int = 18
    var age2: Int = 20
}
var  t = CJLTeacher()
print("end")
Copy the code

Print t: Po t, as can be seen from the figure below, the print of t is the value directly, without any information related to the address

  • Get t’s memory address and view its memory
    • Obtain address:po withUnsafePointer(to: &t){print($0)}
    • Check memory:x/8g 0x0000000100008158

Question: If t is assigned to T1, will t change if T1 is changed?

  • Print t and T1 directly, and you can see that t does not change because t1 changes, mainly becauset1andtIs betweenValue passed, that t1 and T are different memory space, is directlytIs copied tot1In the.t1Changes to the memory space are not affectedtOf memory space

conclusion

  • Structs are value typesAnd the address of the structure is the memory address of the first member
  • Value types
    • Directly in memoryStored value
    • An assignment of a value type is aValue passed“, which is equivalent to a copy of a copy, into different memory space, two Spaces with each otherUnshared state
    • Value passedIn fact, isDeep copy