original articles, welcome reprint. Reprint Please specify: Dongsheng's blog
classes and structs are very similar, and in many cases there is no difference. If you are a designer when designing a system, do you design a class or struct as a type?
Class and struct similarities and differences:
Classes and structs have the following functions:
- Ability to inherit another class
- Ability to check types of run-time objects
- destructor frees resources
- reference count allows one instance to have multiple references
The principle of choice:
Structs are value types, each instance does not have a unique identity, and the following two array instances are inherently indistinguishable, and they can be replaced by each other.
var studentList1: [string] = ["Zhang San", "John Doe", "Harry"]var StudentList2: [string] = ["Zhang San", "John Doe", "Harry"]
But when we refer to classes, it is a reference type and each instance has a unique identity. Let's look at the following employee class Code:
class Employee {
var no = 0
var name = ""
var job = ""
var salary = 0.0
}
var emp1 = Employee()
emp1.no = 100
emp1.name = "Tom"
emp1.job = "SALES"
emp1.salary = 9000
var emp2 = Employee()
emp2.no = 100
emp2.name = "Tom"
emp2.job = "SALES"
emp2.salary = 9000
EMP1 and the EMP2 Two employee instances even though the content is exactly the same, it doesn't mean that they are the same employee, just similar. Each employee instance has a unique identity behind it.
let's look at the department again. Department structural body.
struct Department {
var no: Int = 0
var name: String = ""
}
var dept1 = Department()
dept1.no = 20
dept1.name = "Research"
var dept2 = Department()
dept2.no = 20
dept2.name = "Research"
DepartmentWhy is it designed to be a struct rather than a class, it depends on what we understand about two different departments, if we have the same department number (No) and the department name (namewe think that they are two of the same department, then we can putDepartmentdefined as a struct, which is associated with an employeeEmployeedifferent.
Welcome to follow Dongsheng Sina Weibo@tony_Dongsheng.
Learn about the latest technical articles, books, tutorials and information on the public platform of the smart Jie classroom
?
More ProductsIOS,Cocos, mobile Design course please pay attention to the official website of Chi Jie Classroom:http://www.zhijieketang.com
Smart-Jie Classroom Forum Website:http://51work6.com/forum.php
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Swift 2.0 Study Notes (Day 30)-Choose a class or a struct?