动态类型和多方法

class Pet {

class func printPet(_ pet: Pet){

print("Pet")

}

class func printThem(_ pet1: Pet, _ dog: Dog){

printPet(pet1)

printPet(dog)

}

// 改进后

class func printThem2(_ pet1: Pet, _ dog: Dog){

if let aCat = pet1 as? Cat {

printPet(aCat)

}else if let aDog = pet1 as? Dog {

printPet(aDog)

}

printPet(dog)

}

}

class Cat: Pet {

class func printPet(_ cat: Cat){

print("Cat")

}

}

class Dog: Pet {

class func printPet(_ dog: Dog){

print("Dog")

}

}

//

Pet.printPet(Pet())            // 打印 Pet

Cat.printPet(Cat())            // 打印 Cat

Dog.printPet(Pet())            // 打印 Pet

Pet.printThem(Pet(), Dog())    // 打印 Pet  Pet

// 这里打印 Pet。 打印时的 Dog() 的类型信息并没有被用来在运行时选择合适的 printPet(dog:Dog)版本的方法,而是被忽略掉,并采用了编译期间决定的 Pet 版本的方法。

// 因为 Swift 默认情况下是不采取动态派发的,因此方法的调用只能在编译时决定。

// 要想绕过这个限制,我们可能需要进行通过输入类型做判断和转换。 如上

你可能感兴趣的:(动态类型和多方法)