HTML tutorial
CSS3 tutorial
Bootstrap tutorial
JavaScript tutorial
JQuery tutorial
AngularJS tutorial
React tutorial
NodeJS tutorial
PHP tutorial
Python tutorial
Python3 tutorial
Django tutorial
Linux tutorial
Docker tutorial
Ruby tutorial
Java tutorial
C tutorial
C ++ tutorial
Perl tutorial
JSP tutorial
Lua tutorial
Scala tutorial
Go tutorial
ASP.NET tutorial
C # tutorial
Swift class is the code used to build a general and flexible structure.
We can define the properties (constants, variables) and methods for the class.
And other programming languages are different, Swift does not require you to create custom classes to separate interface and implementation files. You have to do it is to define a class in a single file, the system will automatically generate the code for other external interfaces.
Swift classes and structures have much in common. Common is that:
Compared with the structure, class has the following additional features:
Class classname { Definition 1 Definition 2 …… Definition N }
class student{ var studname: String var mark: Int var mark2: Int }
Instantiate the class:
let studrecord = student()
import Cocoa class MarksStruct { var mark: Int init(mark: Int) { self.mark = mark } } class studentMarks { var mark = 300 } let marks = studentMarks() print("成绩为 \(marks.mark)")
The above program execution output is:
成绩为 300
Attributes of the class can be accessedthrough.The format is:instantiate class name property name:
import Cocoa class MarksStruct { var mark: Int init(mark: Int) { self.mark = mark } } class studentMarks { var mark1 = 300 var mark2 = 400 var mark3 = 900 } let marks = studentMarks() print("Mark1 is \(marks.mark1)") print("Mark2 is \(marks.mark2)") print("Mark3 is \(marks.mark3)")
The above program execution output is:
Mark1 is 300 Mark2 is 400 Mark3 is 900
Because classes are reference types, there may be a plurality of constants and variables at the same time a reference to a class instance in the background.
In order to determined whether the two constants or variables refer to the same class instance, Swift built two identical operators:
Identity operator | Nonidentical operator |
---|---|
Operators are: === | Operators are:! == |
If the two constants or variables reference the same instance of a class return true | If two different constant or variable references a class instance returns true |
import Cocoa class SampleClass: Equatable { let myProperty: String init(s: String) { myProperty = s } } func ==(lhs: SampleClass, rhs: SampleClass) -> Bool { return lhs.myProperty == rhs.myProperty } let spClass1 = SampleClass(s: "Hello") let spClass2 = SampleClass(s: "Hello") if spClass1 === spClass2 {// false print("引用相同的类实例 \(spClass1)") } if spClass1 !== spClass2 {// true print("引用不相同的类实例 \(spClass2)") }
The above program execution output is:
引用不相同的类实例 SampleClass