• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

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

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

声明几个类:

//动物类
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("这是个未知类型")
            }
        }

打印如下:

 


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
[Swift]Alamofire:设置网络请求超时时间【timeout】的两种方式发布时间:2022-07-13
下一篇:
swift-本地通知发布时间:2022-07-14
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap