斯威夫特"是"键入Check Operator

时间:2016-03-10 09:50:21

标签: swift types

我在学习时遇到了问题" Is"在Swift中键入check运算符。我尝试在我的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

我从Apple的博客中学习了以下编程风格。 https://developer.apple.com/swift/blog/?id=23我不知道这是否是一种好的编程风格,因为swift可以进行类型推断。

let dog: Animal = Dog()

2

我猜(anInstance).dynamicType可能是运行时功能,用于检查实例的类型。但是,我没有相关的方法可以调用它。那我该怎么用呢?

3

let dog: Animal = Dog() 

狗实例的类型究竟是什么?动物还是狗? "是"是" operator检查实例的编译器时间类型(Animal)和运行时类型(Dog)?或者甚至我对编译器时间类型和运行时类型的理解都是错误的?

1 个答案:

答案 0 :(得分:0)

参考犬的类型是动物。因此,您可以将其交给使用动物的api。但狗参考背后的实际类型将是Dog。因此,您可以使用is测试实际类型,并且可以使用as

(向下)强制转换为实际类型