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

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

class Shape{
    
}
class Circle:Shape{
    
}
class Rectangle:Shape{
    
}
var shape  = Shape()
var circle = Circle()
var rect = Rectangle()
var array = Array()
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
    }
}

你可能感兴趣的:((二十三)[Swift]类型转换与判断)