Generics 为什么不能使用泛型参数重载函数?
我有一个层应该对手势做出反应。 因此,我的UIView将所有手势转发到此函数(在CALayer子类中) 这段代码可以工作,但我希望像这样重载调用函数Generics 为什么不能使用泛型参数重载函数?,generics,swift,overloading,calayer,Generics,Swift,Overloading,Calayer,我有一个层应该对手势做出反应。 因此,我的UIView将所有手势转发到此函数(在CALayer子类中) 这段代码可以工作,但我希望像这样重载调用函数 func handleGesture<T: UIGestureRecognizer>(gesture: T, atPosition position : CGPoint) { if let hitLayer = hitTest(position)? as? THGestureProtocol {
func handleGesture<T: UIGestureRecognizer>(gesture: T, atPosition position : CGPoint)
{
if let hitLayer = hitTest(position)? as? THGestureProtocol
{
hitLayer.handleGesture(gesture, atPosition: position)
}
}
@objc protocol THGestureProtocol
{
func handleGesture(gesture: UIGestureRecognizer, atPosition position : CGPoint)
func handleGesture(gesture: UITapGestureRecognizer, atPosition position : CGPoint)
func handleGesture(gesture: UIPanGestureRecognizer, atPosition position : CGPoint)
}
func手势测试(手势:T,位置:CGPoint)
{
如果让hitLayer=hitTest(位置)?作为?THGestureProtocol
{
hitLayer.handleGesture(手势、位置:位置)
}
}
@objc协议THGestureProtocol
{
func HandleTesture(手势:手势识别器,atPosition位置:CGPoint)
func HandleTesture(手势:UITapGestureRecognitor,atPosition位置:CGPoint)
func HandleTesture(手势:UIPangesture识别器,atPosition位置:CGPoint)
}
这不管用。只调用第一个函数。那么为什么这不起作用呢 这里描述了这种行为: 长话短说,函数体是用关于T的给定信息编译的,而不是用调用函数的T下的实类型。与C++中的模板相比,这是不同的方法。
class A {}
class B: A {}
class C: A {}
func f(_: A) {
print("A")
}
func f(_: B) {
print("B")
}
func f(_: C) {
print("C")
}
func ff<T: A>(a: T) {
f(a)
}
func gg(a: A) {
f(a)
}
class A{}
B类:A{}
C类:A{}
func f(u:A){
打印(“A”)
}
func f(uu:B){
打印(“B”)
}
func f(u:C){
打印(“C”)
}
func ff(a:T){
f(a)
}
func gg(a:a){
f(a)
}
在本例中,函数ff和gg是等效的。您可能需要在通用函数语句中使用
where子句。你的意思是这样的:手感?不,那没什么区别。这和手艺一样
func handleGesture<T: UIGestureRecognizer>(gesture: T, atPosition position : CGPoint)
{
if let hitLayer = hitTest(position)? as? THGestureProtocol
{
hitLayer.handleGesture(gesture, atPosition: position)
}
}
@objc protocol THGestureProtocol
{
func handleGesture(gesture: UIGestureRecognizer, atPosition position : CGPoint)
func handleGesture(gesture: UITapGestureRecognizer, atPosition position : CGPoint)
func handleGesture(gesture: UIPanGestureRecognizer, atPosition position : CGPoint)
}
class A {}
class B: A {}
class C: A {}
func f(_: A) {
print("A")
}
func f(_: B) {
print("B")
}
func f(_: C) {
print("C")
}
func ff<T: A>(a: T) {
f(a)
}
func gg(a: A) {
f(a)
}