【问题标题】:Swift "Is" Type Check OperatorSwift "Is" 类型检查运算符
【发布时间】:2016-06-25 02:06:06
【问题描述】:

我在 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.

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

let dog: Animal = Dog()

2.

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

3.

let dog: Animal = Dog() 

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

【问题讨论】:

  • 你能帮我解决这个问题吗?@NicolasMiari :]
  • 你读过面向对象的多态性概念吗?
  • @ChristianDietrich 抱歉表达错误。多态性是关于方法的调用。我会在我的问题中纠正这个问题。

标签: swift types


【解决方案1】:

参考狗的类型是动物。因此,您可以将其交给使用 Animals 的 api。但是 dog 引用背后的实际类型是 Dog。因此您可以使用is 测试实际类型,并且可以使用as(向下)转换为实际类型

【讨论】:

  • 能否请您提供更多详细信息,因为您所说的很难理解。
  • 现在我明白了。 “is”会检查引用指向的目标,引用用于api中的参数传递。
猜你喜欢
  • 1970-01-01
  • 2015-10-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-12-09
  • 2015-09-03
相关资源
最近更新 更多