Class versus structure

Similarities between the two
  • Custom properties
  • Define methods
  • You can extend the
  • Follow the agreement
The difference between
  • Classes can inherit, allowing one class to inherit from another
  • Classes are reference types and structs are value types

Type definitions for classes and structures

Structures are usually defined by the keyword struct and classes are defined by class

Struct LGStudent {class LGTeacher {class LGTeacher}Copy the code

Create an instance

Var t= LGTeacher() // create a class object with an instance of tCopy the code

Why are classes reference types and structures value types?

Create both struct and class object instances and add the corresponding attributes

Struct LGStudent {var name: String? var age: Int? } class LGTeacher {// define class var name: String? var age: Int? Var s = LGStudent() s.name=" s1 "s.age=18 var s = s1. Name =" s1" s.age= 19 var t = LGTeacher() Name =" Teacher 2" t1.age=19Copy the code

The output is as follows

The results can be summarized as follows:

  • Structure objects S and S1 are independent of each other. Although S is assigned to S1, S1 copies a new object completely. They do not affect each other, so the structure is a value type
  • Class object t and t1 modification t1 object attribute value, t object attribute values also change accordingly, so it is not hard to see, t is pointed out by their memory address assigned to the t1, changed the address in memory as long as the t1 values, t object corresponding property changed, because the t and t1 are pointing to the same memory address. So a class is a reference type that refers to the same memory address