swift--使用 is 和 as 操作符来实现类型检查和转换 / AnyObject与Any的区别

声明几个类:

//动物类
class Animal{
    
}
//陆地动物类
class terricole: Animal {
    
}
//海洋动物类
class SeaAnimals: Animal {
    
}

1,is 用来做类型检查

 let cat = terricole()
        let fish = SeaAnimals()
        let arr = [cat,fish]
        
        for anima in arr {
            if anima is terricole{
                print("这是陆地动物")
            }else if anima is SeaAnimals{
                print("这是海洋动物")
            }
        }

2, as 用来做类型转换(注:如果不确定类型转换能否成功,可以在 as 后面加问号 “?”)

for animas in arr {
            if let c = animas as? terricole{
                print("这是陆地动物")
            }else if let w = animas as? SeaAnimals{
                print("这是海洋动物")
            }
        }

3,AnyObjective:代表任何class类型的对象实例

let dogs = terricole()
        let shark = SeaAnimals()
        let arrs:[AnyObject] = [dogs,shark]
        
        for animaes in arrs {
            if let d = animaes as? terricole{
                print("这是个爬行动物")
            }else if let e = animaes as? SeaAnimals{
                print("这是个水生动物")
            }
        }

4, Any:范围更广,代表处函数外任何类型的实例

var myAry:[Any] = [Any]()
        myAry.append(1)
        myAry.append("hero11223")
        myAry.append(terricole())
        myAry.append(SeaAnimals())
        print("(myAry)")
        for any in myAry {
            switch any {
            case let any as Int:
                print("这是个int类型")
            case let any as String:
                print("这是个String类型")
            case let any as terricole:
                print("这是个陆地动物类型")
            case let any as SeaAnimals:
                print("这是个水生动物类型")
            default:
                print("这是个未知类型")
            }
        }

打印如下:

原文地址:https://www.cnblogs.com/hero11223/p/7691770.html