• 类型判断


    类型判断与转换

    1.在Object-C中我们经常会对一个id类型或者不确定具体类型的实例对象做类型判断,如isKindOfClass;在Swift中我们可以更简单来实现

    参考:Type Casting

    is类型检查运算符

    //Object-C判断类型

    UIView *v=XXX;

    if([v isKindOfClass:[UIWindow class]) {

    }

    //Swift var v=XXX if v is UIWindow { }

    2.在Object-C中我们要做类型转换可以直接使用C语言的方式来强制类型赋值,但在Swift中需要用as运算符实现

    as 用于向上转型(upcasts) 
    as? 和as! 用于向下转型(Downcasting)

    //Object-C
    for(UIViewController *ct in controllers)
    {
        if([ct isKindOfClass:[MttBaseViewController class]])
        {
            NSLog(@"MttBaseViewController");
        }
        else if([ct isKindOfClass:[MttRootViewController class]])
        {
            NSLog(@"MttRootViewController");
        }
    }
    
    //Swift
    for ct in controllers {
        if let mtt = ct as? MttBaseViewController {
                print("MttBaseViewController")
        } else if let nav = ct as? MttRootViewController {
                print("MttRootViewController")
        }
    }

    当不确定类型转换是否成功时,用类型转换的条件形式( as? ) 
    as?如果失败会返回nil 
    当确定一定是时,用强制形式式( as! )

    两个方法的区别:

    判断对象类型

    -(BOOL) isKindOfClass: classObj判断是否是这个类或者这个类的子类的实例

    -(BOOL) isMemberOfClass: classObj 判断是否是这个类的实例

    测试实例: demo

    类名作为参数进行传递

     1 let item= DoctorGroup()
     2 
     3 let a = InterfaceTests.obtainValues(subObject: item, fatherClass: Group.self)
     4 
     5 
     6 
     7 class func obtainValues<T>(subObject: T, fatherClass: AnyObject.Type) -> AnyCollection<Mirror.Child> {
     8 
     9         
    10 
    11         var so = type(of: subObject)
    12 
    13         
    14 
    15         log.info("---------->(so), (fatherClass)")
    16 
    17         
    18 
    19         while so != fatherClass {    //类与类之间的类型判断
    20             print("------------>true")
    21 
    22         }
    23 
    24    }
    View Code
  • 相关阅读:
    [English Learning]Reading
    [Algorithm]Recurrent Problems_Josephus problem
    字节跳动二面凉经
    2019 Wannafly summer camp Day4
    2019 Wannafly summer camp Day3
    2019 Wannafly summer camp Day2
    暑假补题情况
    2019 Wannafly summer camp Day1
    树形dp学习笔记
    Codeforce Round #553(Div2)
  • 原文地址:https://www.cnblogs.com/EchoHG/p/8759438.html
Copyright © 2020-2023  润新知