class Animal
{
var name:String
init(name:String) {
self.name = name
}
}
class Dog:Animal
{
var color:String
init(name:String,color:String) {
self.color = color
super.init(name: name)
}
}
class Bird:Animal
{
var color:String
init(name:String,color:String)
{
self.color = color
super.init(name: name)
}
}
let animals:[Animal] =
[
Dog(name: "doby", color: "white"),
Dog(name: "ketty", color: "black"),
Dog(name: "notty", color: "red")
]
//使用as!强制将父类类型转换为子类类型
for animal in animals
{
let dog = animal as! Dog
print("Dog:(dog.name),(dog.color)")
}
//使用另一个循环语句强制转换
for animal in animals as! [Dog]
{
print("Dog:(animal.name),(animal.color)")
}
let anims:[Animal] =
[
Dog(name: "kit", color: "black"),
Dog(name: "miky", color: "white"),
Bird(name:"misy",color:"blue"),
Bird(name: "lolly", color: "red")
]
//使用is来判定类型
for item in anims
{
if item is Dog
{
print("i am a dog,my name is (item.name)")
}else if item is Bird
{
print("i am a bird,my name is (item.name)")
}
}
for anim in anims
{
if let dog = anim as?Dog
{
print("i am a dog,my name is (dog.name)")
}else if let bird = anim as? Bird
{
print("i am a bird,my name is (bird.name)")
}
}