欢迎加QQ群讨论:157672725
对象和类
1.创建类: class + 类名
2.类中属性的声明和常量、变量一样,唯一的区别就是它们的上下文是类。方法的声明也一样。
class ClassTest{
var varTest = 0
func desc() -> String {
return "ClassTest with varTest = \(varTest)."
}
}
var test = ClassTest();
test.varTest = 1;
print(test.desc())
输出:ClassTest with varTest = 1.
3.构造函数: init + 参数列表
4.self用来区别实例变量与参数
class ClassTest{
var varTest = 0
init(){
varTest = -1;
}
init(varTest : Int){
self.varTest = varTest
}
func desc() -> String {
return "ClassTest with varTest = \(varTest)."
}
}
5.析构函数:deinit
class ClassA {
var varStr = "sss";
}
class ClassTest{
var varTest = 0
var varA: ClassA? = ClassA()
init(){
varTest = -1;
}
init(varTest : Int){
self.varTest = varTest
}
func desc() -> String {
return "ClassTest with varTest = \(varTest)."
}
deinit{
varA = nil;
}
}
6.继承: :SuperClass
7.使用 super访问父类方法
8.使用 override覆盖父类方法
class ClassTrue: ClassTest {
init(varTest :Int ,varStr :String) {
super.init(varTest: varTest)
}
override func desc() -> String {
return "ClassTrue with varTest = \(varTest)."
}
}
9.属性: 使用闭包实现 get{ return XXX } set{ XXX = newValue }
10.属性中新值的名字是newValue
class ClassTest{
var varTest = 0
var varA: ClassA? = ClassA()
var varGettersSetters: Int {
get {
return varTest
}
set {
varTest = newValue
}
}
init(){
varTest = -1;
}
init(varTest : Int){
self.varTest = varTest
}
func desc() -> String {
return "ClassTest with varTest = \(varTest)."
}
deinit{
varA = nil;
}
}
var test = ClassTest();
test.varTest = 1;
test.varGettersSetters = 100;
print(test.desc())
输出:ClassTest with varTest = 100.