美文网首页
swift类型检查(is操作符)

swift类型检查(is操作符)

作者: BetterComingDay | 来源:发表于2017-06-26 17:47 被阅读8次

    类型检查操作符 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 学生
    

    相关文章

      网友评论

          本文标题:swift类型检查(is操作符)

          本文链接:https://www.haomeiwen.com/subject/beujcxtx.html