类型检查操作符 is 可以检查一个对象是不是某个类的对象。
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 item is Teacher{
print("1",item.name)
}else if item is Stutent{
print("2",item.name)
}
}
控制台:
1 老师
2 学生
网友评论