Enumerations, structs, classes
注:本文为作者自己总结。过于基础的就不再赘述 ,都是亲自測试的结果。如有错误或者遗漏的地方。欢迎指正,一起学习。
1. Enumeration
Enumerations are a set of related values that define a common set of types, and enum
keywords case
indicate that a new row of member values will be defined.
enum Direction{ case East case West case South case North}
This defines a simple enumeration type with four enumeration elements in it.
can also be used in one line of form
enum Direction{ case East , West , South , North}
Be able to access this enumeration type in this way var dir = Direction.East
. This time the variable dir
has been judged Direction
, and once again the assignment can be directly using the phrase method dir = .West
.
- Correlation value (associated values)
You can define Swift's enumeration store regardless of the type of correlation value, assuming that the data type of each member can be different.
enum Barcode { case UPCA(IntIntInt ,Int ) case QRCode(String)}
You can assign a value to it like this var pro = Barcode.UPCA(8, 53627, 29009, 1)
. You can change pro = .QRCode("DSLEKWLJELJAIWFLWKJF")
that.
This takes value
switch pro{case .UPCA(let a1,letletlet a4): print("\(a1) , \(a2) , \(a3) , \(a4)")case .QRCode(let s): print(s)}
You can also write let on the front
switch pro{caselet .UPCA( a1, a2, a3, a4): print("\(a1) , \(a2) , \(a3) , \(a4)")caselet .QRCode(s): print(s)}
Both get the same result: DSLEKWLJELJAIWFLWKJF
- Specify a specific type for the enumeration (original value)
You can specify a type for an enumeration. For example, String type.
enum SignBuilding : String{ case"天安门" case"兵马俑"}
The enumeration is defined here as a string type.
This allows the corresponding value to be obtained.print(SignBuilding.Beijing.rawValue)
It is also possible to implicitly assign values to primitive values
enum IntVal:Int { case1 , Val2 , Val3}
Suppose you don't assign a value to Val1. The default is 0. Increment is 1, you can also set the initial value (here we given the initial value of 1)
It is also possible to initialize the enumeration with the original value let val = IntVal(rawValue: 2)
print(val) //Optional(IntVal.Val2)
, and the result is the optional type, since not all numbers can match the corresponding enumeration type. such as: let errorVal = IntVal(rawValue: 5)
print(errorVal) //nil
The official also gave the recursive enumeration, the keyword indirect
. But I have tried many times, this key word also did not change color, also will error.
enum Calculate{ case Num(Int) case Plus(Calculate,Calculate) case ChenFa(Calculate,Calculate)}
Search on the Internet, because it is a new feature of 2.0. There is not much explanation on the Internet. We can study it. I also study, and then come up with the study to fill up.
Enumeration inside can also have methods, but not very recommended. Fully capable of using structures and methods.
Both enumerations and struct bodies are value types. are copied in the same way as they are delivered.
A class is a reference type and is passed only when a reference is passed.
2. Class and Structure
Class
struct
simple definition of class struct body
struct myPoint{ var0; var0;}class Person { var name:String?
; var age:Int?; var12); var p = myPoint(); }
This defines a simple struct and class in which a few simple attributes are defined, including a struct property, and two methods of initialization are given. The declaration of attributes can be seen in a--– variable declaration in Swift's specific interpretation.
Int, float. Array dictionaries, and so on, are all value types. The background is implemented in a structured way
General use of structural body conditions
- The main purpose of the structure is to encapsulate a small number of simple data values
- An estimate instance will be copied instead of referenced during assignment or delivery
- Regardless of what value type attributes are stored in the struct, they will be copied instead of referenced
- There is no need to inherit the existing type or attribute behavior (struct is not inherited)
Suppose you create an instance of a struct. And assigning this instance to a constant cannot alter its properties. Even the variable attribute cannot be changed
let11)
Here I try to change the variable x in the struct to error.
A reference type is assigned to a constant and can still change its variable properties. So an instance of a class can be assigned a value to a constant
A deferred store property is a property whose initial value is evaluated when it is first called.
Use lazy to mark a deferred storage property before the property declaration. (Lazy Loading)
注意:必须将延迟存储属性声明成变量(使用var关键字),由于属性的值在实例构造完毕之前可能无法得到。而常量属性在构造过程完毕之前必须要有初始值,因此无法声明成延迟属性。
Take a look at an official sample.
class DataImporter { /* DataImporter 是一个将外部文件里的数据导入的类。 这个类的初始化会消耗不少时间。 */ var"data.txt" // 这是提供数据导入功能}
class DataManager { lazyvar importer = DataImporter() //这里使用了懒载入 在第一次用到的时候才去创建这个实例 假设创建DataManager 就去创建DataImporter 有可能并不须要这个实例。浪费内存和时间 var data = [String]() // 这是提供数据管理功能}
let manager = DataManager()manager.data.append("Some data")manager.data.append("Some more data")// DataImporter 实例的 importer 属性还没有被创建
Here we can see that we are not using dataimporter, so we do not need to initialize the Dataimporter when we create the DataManager (), so we use lazy loading to save memory at this time.
But. Suppose that the attribute of the tagged bit lazy is visited by multiple threads when it is not initialized. This property is not guaranteed to be instantiated only once
We can define a read-only property in the following way.
var1.2;var b:Double{ return a*4 }
- Type property
No matter how many instances of this class, it has only one class property.
Key wordsstatic
struct myStruct{ staticvar19.3}
Ability to invoke type properties directly from the struct's name or class nameprint(myStruct.height)
It is only sometimes necessary to use the keyword in a class class
to agree to its subclasses overriding this property.
class myclass { static let name = "Zhangsan" static var age = 21 static var status:int {return 1 } //can use the keyword class to support subclasses overriding a parent class when defining computed properties
class
var
canoverrid :
int {
return
10 }}
class sonClass: myClass { overridestaticvar return89 } //static let name = "zhangsan " //cannot override with a stored property ‘name‘}
Here our subclasses can override class
the tag's Type property.
- Method
Methods can be divided into instance methods and type methods.
Classes, structs, enumerations can define instance methods, and instance methods encapsulate specific tasks and functions for instances of a given type. Classes, structs, enumerations can also define type methods, and type methods are associated with the type itself.
Structure and enumeration can be defined by a large difference between swift and OC
The type method is to add the static class in front of the func and sometimes it may need to add class.
Is the same as the use of properties, this is not an instance.
A property of a value type cannot be altered in an instance method. But sometimes you really want to change it. At this point you can use the mutation method.
Key Words mutating
struct Counter{ var count = 0 func getCount() ->Int{ return count } //由于值类型的属性不能在实例方法中被改动 这里使用了变异方法 func increment() { count++ }}var c = Counter()print// 0print// 0c.increment()print// 1
The mutation method can assign itself to a value
enum Level { case High , Mid ,Low mutating func next() { switchself { case .High: self = Mid case .Mid: self = Low default: self = High } }}var level = Level.Highlevel.next()print(level) //Level.Midlevel.next()print(level) //Level.Low
Learn iOS. There he is enough, little brother video, wisdom, dark horse, all kinds of swift books
Swift specifically explains the six----------------enumerations, structs, classes