Swift for iOS Development (8)-Classes and Structures

version

Xcode 11.3.1
Swift 5.1.3

The functions of structures and classes in Swift are very similar. Most of the functions discussed in this article can be used on structures or classes, so put the two in the same chapter.

Structure and class comparison

Structures and classes in Swift have a lot in common. Both can be:

  • Define attributes to store values
  • Define methods to provide functionality
  • Define subscript operations to access their values ​​through subscript syntax
  • Define the constructor to set the initial value
  • Extend to increase functionality beyond the default implementation
  • Follow the protocol to provide a certain standard function

Compared with the structure, the class has the following additional functions:

  • Inheritance allows one class to inherit the characteristics of another class
  • Type conversion allows checking and interpreting the type of a class instance at runtime
  • The destructor allows a class instance to release any allocated resources
  • Reference counting allows multiple references to a class

Choose structure or class?
The additional functionality supported by the class comes at the cost of increased complexity. According to general guidelines, consider building a structure when one or more of the following conditions are met:

  • The main purpose of the structure is to encapsulate a small amount of related simple data values.
  • It is reasonable to expect that when a structure instance is assigned or passed, the encapsulated data will be copied rather than referenced.
  • Any value type attributes stored in the structure will also be copied instead of being quoted.
  • The structure does not need to inherit the properties or behaviors of another existing type.

For example, structures are suitable for use in the following situations:

  • The size of the geometric shape encapsulates a width property and a height property, both of which are of Double type.
  • A path within a certain range encapsulates a start attribute and a length attribute, both of which are of type Int.
  • A point in the three-dimensional coordinate system encapsulates the x, y and z attributes, all of which are of Double type.

Type definition & create instance

// 定义结构体
struct Characteristic {
    
    
    var height = 0
    var weight = 0
}

// 定义类
class People {
    
    
    var name: String?
    var age = 0
    var characteristic = Characteristic()
}

// 实例化
// 类的实例化
let people = People()
// 结构体的实例化
var characteristic1 = Characteristic()
// 结构体的另一种方法实例化 (成员逐一构造器,类没有这种方法)
let characteristic2 = Characteristic(height: 180, weight: 200)

people.name = "小明"
people.age = 18
people.characteristic.height = 180
people.characteristic.weight = 150
print("\(people.name!)的年龄是\(people.age)岁,身高是\(people.characteristic.height)厘米,体重是\(people.characteristic.weight)斤")
// 小明的年龄是18岁,身高是180厘米,体重是150斤

characteristic1.height = 100;
characteristic1.weight = 50;
print("特征1 身高为\(characteristic1.height), 体重为\(characteristic1.weight)")
// 特征1 身高为100, 体重为50

print("特征2 身高为\(characteristic2.height), 体重为\(characteristic2.weight)")
// 特征2 身高为180, 体重为200

Structure is a value type

A value type is a type whose value is copied when it is assigned to a variable, constant, or passed to a function.
For example, declare a feature 3 and assign the value of feature 2 to the former, then change the height and weight of feature 3, and find that the value in feature 2 does not follow the change:

var characteristic3 = characteristic2
characteristic3.height = 200
characteristic3.weight = 300
print("特征2 身高为\(characteristic2.height), 体重为\(characteristic2.weight)")
print("特征3 身高为\(characteristic3.height), 体重为\(characteristic3.weight)")
// 特征2 身高为180, 体重为200
// 特征3 身高为200, 体重为300

In fact, all the basic types in Swift: integer, floating-point number, boolean, string, array and dictionary are all value types , The bottom layer is also implemented using structure.

Class is a reference type

Unlike value types, when a reference type is assigned to a variable, constant, or passed to a function, its value will not be copied. Therefore, a reference to an existing instance is used, not a copy of it.
For example, declare a people1 and assign people to him, then change the name of people1, and find that the original people have also changed

let people1 = people
people1.name = "小红"
print("people 名称为\(people.name!)")
print("people1 名称为\(people1.name!)")
// people 名称为小红
// people1 名称为小红

Note that people1 is declared as a constant and not a variable. However, you can still change properties such as people1.name, because the value of the constant people1 has not changed. They do not "store" this People instance, but merely a reference to the People instance. So, what changed is the name attribute of the underlying People instance, not the value of the constant reference to People.

Identity operator

Because the class is a reference type, multiple constants and variables may refer to the same class instance at the same time behind the scenes. (For structures and enumerations, this is not true. Because they are value types, their values ​​will always be copied when they are assigned to constants, variables, or passed to functions.)
Determine whether two constants or variables are referenced The same class instance is sometimes useful. To achieve this goal, Swift provides two identity operators:

  • The same (===)
  • Not the same (!==)
if people1 === people {
    
    
    print("people1 和 people 引用同一个实例")
}
// 打印 people1 和 people 引用同一个实例

pointer

If you have experience in C, C++, or Objective-C languages, then you may know that these languages ​​use pointers to refer to addresses in memory. Swift refers to a constant or variable of a reference type instance, which is similar to a pointer in C language, but it does not directly point to a memory address, nor does it require you to use an asterisk (*) to indicate that you are creating a reference . In contrast, references in Swift are defined in the same way as other constants or variables.

Guess you like

Origin blog.csdn.net/u012078168/article/details/104350158