zoukankan      html  css  js  c++  java
  • 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("这是个未知类型")
                }
            }

    打印如下:

  • 相关阅读:
    C++的几个晦涩特性
    高效学习的工具Mnemosyne
    允许OSQA上传任意类型的文件
    新一代J2ME终端标准MSAfor CLDC——解读JSR248
    JAVA实现简单的HTTP服务器
    什么是Web 2.0
    Java 手机与空间制图服务(WMS)应用集成
    广西移动SP结算工作管理流程
    2007年Enterprise 2.0的10大趋势
    移动虚拟专用网的发展与未来应用
  • 原文地址:https://www.cnblogs.com/hero11223/p/7691770.html
Copyright © 2011-2022 走看看