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

2016-08-19  本文已影响99人  修行猿

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! 转换

let s1 = shape as? Circle
s1.dynamicType
let s2 = array.first as! Shape
s2.dynamicType   //Circle.Type
//let s3 = array.first as! Rectangle //报错
//方式一
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
    }
}
上一篇 下一篇

猜你喜欢

热点阅读