(二十三)[Swift]类型转换与判断

1.以下面代码为情境代码

class Shape{
    
}
class Circle:Shape{
    
}
class Rectangle:Shape{
    
}
var shape  = Shape()
var circle = Circle()
var rect = Rectangle()
var array = Array<Any>()
array.append(circle)
array.append(shape)
array.append(rect)
array.append("aaaa")
array.append({return "aaaaa"})

2.is 用来判断对象是否属于某个类或者其子类,相当于OC中的isKindOf方法

for item in array{
    if item is Rectangle{
        print("Rectangle:\(item)")
    }else if item is Circle{
        print("Circle:\(item)")
    }
    
}

3.as as? as! 转换

  • as? 转换成功之后是一个optional类型的值,转换失败为nil
let s1 = shape as? Circle
s1.dynamicType
  • as! 转换成功后是原类型不是目标类型,转换失败报错
let s2 = array.first as! Shape
s2.dynamicType   //Circle.Type
//let s3 = array.first as! Rectangle //报错
  • as 当编译器也知道一定能转成功的时候可以用as
//方式一
let s4 = shape as Shape
s4.dynamicType
//方式二
for item in array{
    switch item {
    case is Circle:
        print("circle")
    case is Rectangle:
        print("rectangle")
    case let s3 as Shape:
        print(s3)
    default:
        break
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容