我试图理解为什么泛型方法的 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!")
}
好的,现在让我们运行一些测试。如果我们有:
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)
}
输出是:
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
嗯......显然,为了使where
协议子句起作用,我们需要传递一个符合其定义中协议的强类型。
仅使用超类型是不够的,即使在测试#3 中很明显给定实例实际上符合HasChildren
协议。
那么,我在这里缺少什么,这是不可能的吗?您是否有一些链接可以提供有关正在发生的事情的更多信息,或者有关where
子句或子类型及其一般行为的更多信息?
我已经阅读了一些有用的资源,但似乎没有一个关于它为什么不起作用的详尽解释: