class MySubClassOne: MyClass { var count:Int? } class MySubClassTwo: MyClass { var isBiger:Bool? } //创建3个实例 var obj1 = MyClass() obj1.name = "HS" var obj2 = MySubClassOne() obj2.count = 100 var obj3 = MySubClassTwo() obj3.isBiger=true //将实例存放在其公共父类类型的数组集合中 var array:[MyClass] = [obj1,obj2,obj3] //进行遍历 forvar i in0..<array.count { var obj = array[i] if obj is MySubClassOne { print((obj as! MySubClassOne).count!) continue } if obj is MySubClassTwo { print((obj as! MySubClassTwo).isBiger!) continue } if obj is MyClass { print(obj.name!) } }
//进行遍历 forvar i in0..<array.count { var obj = array[i] if obj is MySubClassOne { print((obj as! MySubClassOne).count!) continue } if obj is MySubClassTwo { print((obj as! MySubClassTwo).isBiger!) continue } if obj is MyClass { print((obj as! MyClass).name!) } }
Any类型则比AnyOject类型更加强大,其可以混合值类型和引用类型一起工作,示例如下:
1
var anyArray:[Any] = [100,"HS",obj1,obj2,false,(1.1),obj3,{()->() in print("Closures")}]