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

本文介绍了Swift中的类型检查(is)和类型转换(as)操作符的使用方法,并通过具体示例展示了如何利用这些特性来处理不同类型的对象实例。

声明几个类:

//动物类
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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值