Swift 类@H_404_5@
Swift 类是构建代码所用的一种通用且灵活的构造体。@H_404_5@
我们可以为类定义属性(常量、变量)和方法。@H_404_5@
与其他编程语言所不同的是,Swift 并不要求你为自定义类去创建独立的接口和实现文件。你所要做的是在一个单一文件中定义一个类,系统会自动生成面向其它代码的外部接口。@H_404_5@
类和结构体对比@H_404_5@
Swift 中类和结构体有很多共同点。共同处在于:@H_404_5@
定义附属脚本用于访问值@H_404_5@
继承允许一个类继承另一个类的特征@H_404_5@
类型转换允许在运行时检查和解释一个类实例的类型@H_404_5@
解构器允许一个类实例释放任何其所被分配的资源@H_404_5@
引用计数允许对一个类的多次引用@H_404_5@
语法:@H_404_5@
Class classname {@H_404_5@
Definition 1@H_404_5@
Definition 2@H_404_5@
……@H_404_5@
Definition N@H_404_5@
}@H_404_5@
类定义@H_404_5@
class student{@H_404_5@
var studname: String@H_404_5@
var mark: Int@H_404_5@
var mark2: Int@H_404_5@
}@H_404_5@
实例化类:@H_404_5@
let studrecord = student()@H_404_5@
实例@H_404_5@
import Cocoa@H_404_5@
@H_404_5@
class MarksStruct {@H_404_5@
var mark: Int@H_404_5@
init(mark: Int) {@H_404_5@
self.mark = mark@H_404_5@
}@H_404_5@
}@H_404_5@
@H_404_5@
class studentMarks {@H_404_5@
var mark = 300@H_404_5@
}@H_404_5@
let marks = studentMarks()@H_404_5@
print("成绩为 \(marks.mark)")@H_404_5@
成绩为 300@H_404_5@
类的属性可以通过 . 来访问。格式为:实例化类名.属性名:@H_404_5@
import Cocoa@H_404_5@
@H_404_5@
class MarksStruct {@H_404_5@
var mark: Int@H_404_5@
init(mark: Int) {@H_404_5@
self.mark = mark@H_404_5@
}@H_404_5@
}@H_404_5@
@H_404_5@
class studentMarks {@H_404_5@
var mark1 = 300@H_404_5@
var mark2 = 400@H_404_5@
var mark3 = 900@H_404_5@
}@H_404_5@
let marks = studentMarks()@H_404_5@
print("Mark1 is \(marks.mark1)")@H_404_5@
print("Mark2 is \(marks.mark2)")@H_404_5@
print("Mark3 is \(marks.mark3)")@H_404_5@
Mark1 is 300@H_404_5@
Mark2 is 400@H_404_5@
Mark3 is 900@H_404_5@
恒等运算符@H_404_5@
因为类是引用类型,有可能有多个常量和变量在后台同时引用某一个类实例。@H_404_5@
为了能够判定两个常量或者变量是否引用同一个类实例,Swift 内建了两个恒等运算符:@H_404_5@
恒等运算符 不恒等运算符@H_404_5@
运算符为:=== 运算符为:!==@H_404_5@
如果两个常量或者变量引用同一个类实例则返回 true 如果两个常量或者变量引用不同一个类实例则返回 true@H_404_5@
实例@H_404_5@
import Cocoa@H_404_5@
@H_404_5@
class SampleClass: Equatable {@H_404_5@
let myProperty: String@H_404_5@
init(s: String) {@H_404_5@
myProperty = s@H_404_5@
}@H_404_5@
}@H_404_5@
func ==(lhs: SampleClass,rhs: SampleClass) -> Bool {@H_404_5@
return lhs.myProperty == rhs.myProperty@H_404_5@
}@H_404_5@
@H_404_5@
let spClass1 = SampleClass(s: "Hello")@H_404_5@
let spClass2 = SampleClass(s: "Hello")@H_404_5@
@H_404_5@
if spClass1 === spClass2 {// false@H_404_5@
print("引用相同的类实例 \(spClass1)")@H_404_5@
}@H_404_5@
@H_404_5@
if spClass1 !== spClass2 {// true@H_404_5@
print("引用不相同的类实例 \(spClass2)")@H_404_5@
}@H_404_5@
引用不相同的类实例 SampleClass@H_404_5@