类型转换就是将一个类型转换为另一个类型,类型转换只能发生在子父类之间。
其实类型转换就是java里边的父类的引用指向了子类的对象,有多态的嫌疑,哈哈哈。
类型转换操作符有两种形式:as? 和 as! 。
as? 操作符将对象转换为目标类型的可选类型,转换失败返回nil
as! 操作符会强制解包,转换失败会触发运行时错误
class Person{
var name:String
init (name:String){
self.name = name
}
}
class Teacher:Person{
var school:String
init (name:String, school:String){
self.school = school
super.init(name: name)
}
}
class Stutent:Person{
var age:Int
init (age:Int, name:String){
self.age = age
super.init(name: name)
}
}
let tea = Teacher(name:"老师", school:"北工大")
let stu = Stutent(age:23, name:"学生")
let array = [tea, stu];
for item in array{
if let temp=item as? Teacher{
print("1",temp.school)
}else if let temp=item as? Stutent{
print("2",temp.age)
}
}