1、属性的继承
子类可以继承父类的属性,包括存储属性、计算属性和类型属性
class Person{
//存储属性
var age = 20
//计算属性
var description: String{
return "我现在\(self.age)岁了"
}
//类型属性
static var kind = "Chinese"
}
class Teacher : Person{}
let teacher = Teacher()
print(teacher.age,teacher.description,"\(Teacher.kind)")
控制台:
20 我现在20岁了 Chinese
2、属性观察器的继承
class Person{
//存储属性
var age = 20{
willSet{
print("age即将被赋值\(newValue)")
}
didSet{
if(age > oldValue){
print("新赋值的值比原来的大")
}else{
print("新赋值的值比原来的小")
}
}
}
}
class Teacher : Person{}
var t:Teacher = Teacher()
t.age = 19
控制台:
age即将被赋值19
新赋值的值比原来的小
3、下标脚本的继承
class Person{
subscript (index:Int) -> String{
switch index{
case 1:
return "1"
case 2:
return "2"
case 3:
return "3"
default:
return "default"
}
}
}
class Teacher : Person{}
let teacher = Teacher()
print(teacher[1],teacher[6])
控制台:
1 default
4、方法的继承
包括对象方法和类方法
class Person{
func description(){
print("我是Person的方法")
}
}
class Teacher : Person{}
let teacher = Teacher()
teacher.description()
控制台:
我是Person的方法
5、增加新属性和方法
class Person{
subscript (index:Int) -> String{
switch index{
case 1:
return "1"
case 2:
return "2"
case 3:
return "3"
default:
return "default"
}
}
func run(){
print("Person is running")
}
}
class Teacher : Person{
let age = 15
func walk(){
print("Teacher is walking")
}
}
let person = Person()
let teacher = Teacher()
person.run()
teacher.walk()
print(teacher.age)
控制台:
Person is running
Teacher is walking
15