gpt4 book ai didi

swift - Swift 中的类型检查是如何工作的

转载 作者:可可西里 更新时间:2023-11-01 01:52:25 26 4
gpt4 key购买 nike

我很好奇类型检查是如何与 Swift 一起工作的,我试了一下并创建了一个 Living 类和一个继承自 Animal 类>生活类。 Cat 类继承自 Animal 类,Dog 类没有任何父类。

到目前为止我的类(class)层次结构:

class Living {
let heartRatePerMin: Int
init(heartRatePerMin: Int) {
self.heartRatePerMin = heartRatePerMin
}
}

class Animal: Living {
let name: String

init(name: String, heartRatePerMin: Int) {
self.name = name
super.init(heartRatePerMin: heartRatePerMin)
}
}

class Cat: Animal {
let meowsPerHour: Int

init(meowsPerHour: Int, name: String) {
self.meowsPerHour = meowsPerHour
super.init(name: name, heartRatePerMin: 60)
}
}

class Dog {
let runningSpeed: Int

init(runningSpeed : Int) {
self.runningSpeed = runningSpeed
}
}

首先,当我创建动物、狗和猫的实例时。我收到关于检查是否总是失败或成功的警告。我检查类型和获取警告的方式:

let animal = Animal(name: "Daisy", heartRatePerMin: 80)
let dog = Dog(runningSpeed: 2)
let cat = Cat(meowsPerHour: 10, name: "Smokey")

if animal is Animal {
//Warning: 'is' test always true
}

if dog is Animal {
//Warning: Cast from 'Dog' to unrelated type 'Animal' always fails
}

if cat is Animal {
//Warning: 'is' test always true
}

if cat is Living {
//Warning: 'is' test always true
}

到目前为止,我相信编译器会检查给定的对象类是否具有对正在检查的类型的继承,并且可以发出警告。

然后我创建了一个空的 Grumpy 协议(protocol):

protocol Grumpy {

}

在那之后,我从我的 Cat 类中遵从了 Grumpy,但是我从我的 Dog 类中没有遵从。

现在,当我如下检查我的对象(猫和狗)的类型是否为 Grumpy 时,我收到了 cat 的警告,因为 Cat 类符合 Grumpy 协议(protocol),但我没有得到任何关于狗的警告。它什么也没说。但是当我检查 dog 是否是上面的 Animal 类型时,它发出警告说它总是会失败。为什么它不能为这种情况提供相同的信息?

    if cat is Grumpy {
//Warning: 'is' test is always true
}

if dog is Grumpy {
//Nothing
}

然后,鉴于我缺乏 CS 和 Swift 知识,我还尝试做一些其他事情来查看它的行为方式,我创建了一个 Any 数组作为 anyArray。然后创建一个变量unknown,将cat 转换为Any 等于unknown。然后将 unknown 附加到 anyArray。之后,我尝试键入检查 anyArray 的第一个索引是否为 Cat 类型,但同样没有警告:

    var anyArray = [Any]()
let unknown = cat as Any
anyArray.append(unknown)

if anyArray[0] is Cat {
//Nothing.
}

鉴于我尝试过的所有事情,我很好奇编译时和运行时的类型检查是如何工作的?我知道这是一个有点长的问题,但我们将不胜感激。

最佳答案

我假设您知道以下内容是有效的以及原因:

// although living is of type Living, it stores an instance of Cat at runtime
let living: Living = Cat(meowsPerHour: 10, name: "Smokey")

让我们先检查一下:

if dog is Grumpy {
//Nothing
}

dogDog 类型,但是编译器不知道在运行时 dog 是否会存储 的子类>Dog,它确实符合 Grumpy。如果像这样分配 dog,则将运行 if 语句:

class GrumpyDog : Dog, Grumpy {
// ...
}

dog = GrumpyDog(...)

if anyArray[0] is Cat {
//Nothing.
}

这是因为 anyArray[0]Any 类型。编译器不够聪明,无法知道在运行时,anyArray[0] 存储了一个 Cat。因此,不能确定 is 的计算结果为真。 “如果它实际上是一只呢?”它可能会说。

关于swift - Swift 中的类型检查是如何工作的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53824633/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com