调用错误的泛型重载函数

Yoa*_*ges 5 generics ios subtyping swift

我试图理解为什么忽略泛型方法的where子句

我在Swift 3中做了一个简单的用例(你可以在操场上复制代码,如果你想要它的话):

//MARK: - Classes

protocol HasChildren {
    var children:[Human] {get}
}

class Human {}

class SeniorHuman : Human, HasChildren {
    var children: [Human] {
        return [AdultHuman(), AdultHuman()]
    }
}

class AdultHuman : Human, HasChildren {
    var children: [Human] {
        return [YoungHuman(), YoungHuman(), YoungHuman()]
    }
}

class YoungHuman : Human {}

//MARK: - Generic Methods

/// This method should only be called for YoungHuman
func sayHelloToFamily<T: Human>(of human:T) {
    print("Hello \(human). You have no children. But do you conform to protocol? \(human is HasChildren)")
}

/// This method should be called for SeniorHuman and AdultHuman, but not for YoungHuman...
func sayHelloToFamily<T: Human>(of human:T) where T: HasChildren {
    print("Hello \(human). You have \(human.children.count) children, good for you!")
}
Run Code Online (Sandbox Code Playgroud)

好的,现在让我们进行一些测试.如果我们有:

let senior = SeniorHuman()
let adult = AdultHuman()

print("Test #1")
sayHelloToFamily(of: senior)

print("Test #2")
sayHelloToFamily(of: adult)

if let seniorFirstChildren = senior.children.first {
    print("Test #3")
    sayHelloToFamily(of: seniorFirstChildren)

    print("Test #4")
    sayHelloToFamily(of: seniorFirstChildren as! AdultHuman)
}
Run Code Online (Sandbox Code Playgroud)

输出是:

Test #1
Hello SeniorHuman. You have 2 children, good for you!

Test #2
Hello AdultHuman. You have 3 children, good for you!

Test #3
Hello AdultHuman. You have no children. But do you conform to protocol? true
//Well, why are you not calling the other method then?

Test #4
Hello AdultHuman. You have 3 children, good for you!
//Oh... it's working here... It seems that I just can't use supertyping
Run Code Online (Sandbox Code Playgroud)

嗯......显然,where要使协议子句起作用,我们需要传递一个符合其定义中的协议的强类型.

即使在测试#3中显而易见的是,给定实例实际上符合HasChildren协议,仅使用超类型是不够的.

那么,我在这里想念的是,这是不可能的?您是否有一些链接提供有关正在发生的事情的更多信息where,或者有关子句或子类型及其行为的更多信息?

我已经阅读了一些有用的资源,但似乎没有一个详尽的解释为什么它不起作用:

Sul*_*han 3

要调用的方法的类型是在编译时选择的。编译器对你的类型了解多少?

if let seniorFirstChildren = senior.children.first {
Run Code Online (Sandbox Code Playgroud)

seniorFirstChildrenHuman因为这就是children声明的方式。我们不知道该人是否child是成年人或老年人。

但是,请考虑一下:

if let seniorFirstChildren = senior.children.first as? AdultHuman {
Run Code Online (Sandbox Code Playgroud)

现在编译器知道了seniorFirstChildrenAdultHuman,它将调用您期望的方法。

您必须区分静态类型(编译期间已知的类型)和动态类型(运行时已知的类型)。