Swift";是";类型检查操作员

Swift";是";类型检查操作员,swift,types,Swift,Types,我在学习Swift中的“Is”类型检查运算符时遇到了一个问题。我在Xcode中尝试了以下代码,结果在控制台中打印出来,这让我很困惑 class Animal {} class Dog: Animal {} let dog: Animal = Dog() let anotherDog = Dog() print("\(dog.dynamicType)") //printed "(Dog #1)" if dog is Animal { print("dog is an Animal") /

我在学习Swift中的“Is”类型检查运算符时遇到了一个问题。我在Xcode中尝试了以下代码,结果在控制台中打印出来,这让我很困惑

class Animal {}
class Dog: Animal {}
let dog: Animal = Dog()
let anotherDog = Dog()

print("\(dog.dynamicType)") //printed "(Dog #1)"

if dog is Animal {
   print("dog is an Animal") //printed
}

if dog is Dog {
   print("dog is a dog") //printed
 }

if anotherDog is Animal {
   print("another dog is an Animal") //printed
}
以下是我的困惑:

1. 我从苹果的博客上学到了以下编程风格。我不知道这是否是一种好的编程风格,因为swift可以进行类型推断

let dog: Animal = Dog()
2. dynamicType可能是检查实例类型的运行时功能。但是,没有相关的方法可以调用。那我怎么用呢

3.
狗的具体类型是什么?动物还是狗?“Is”运算符是否同时检查实例的编译器时间类型(Animal)和运行时类型(Dog)?甚至我对编译器时间类型和运行时类型的理解也是错误的?

参考狗的类型是动物。因此,您可以将其交给使用动物的api。但是dog引用后面的实际类型将是dog。因此,您可以使用
is
测试实际类型,也可以使用
as

转换为实际类型。您能帮我吗?@NicolasMiari:]您是否阅读了面向对象的多态性概念?@ChristiandeTrich对于错误的表达式表示抱歉。多态性是指方法的调用。我会在我的问题中纠正这一点。你能提供我更多的细节吗,因为你所说的很难理解。现在我明白了。“Is”将检查引用指向的目标,引用用于在api中传递参数。
let dog: Animal = Dog()