【问题标题】:why can I not use a generic parameter to overload a function?为什么我不能使用泛型参数来重载函数?
【发布时间】:2014-09-01 15:12:50
【问题描述】:

我有一个应该响应手势的层。 所以我的 UIView 将所有手势转发给这个函数(在一个 CALayer 子类中)。

func handleGesture<T: UIGestureRecognizer>(gesture: T, atPosition position : CGPoint)
    {
        if let hitLayer = hitTest(position)? as? THGestureProtocol
        {
            if let tapGesture = gesture as? UITapGestureRecognizer
            {
                hitLayer.handleTapGesture(tapGesture, atPosition: position)
            }
            else
            {
                hitLayer.handleGesture(gesture, atPosition: position)
            }
        }
    }

此函数然后查找适当的子层并转发手势。

@objc protocol THGestureProtocol
{
    func handleGesture(gesture: UIGestureRecognizer,    atPosition position : CGPoint)
    func handleTapGesture(gesture: UITapGestureRecognizer, atPosition position : CGPoint)
    func handleDragGesture(gesture: UIPanGestureRecognizer, atPosition position : CGPoint)
}

这段代码有效,但我希望像这样重载调用函数

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)
}

这不起作用。只有第一个函数被调用。那么为什么这不起作用呢?

【问题讨论】:

标签: generics swift overloading calayer


【解决方案1】:

此处描述了此行为:https://forums.developer.apple.com/message/17580#17580

长话短说,函数体是使用关于 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)
}

在此示例中,函数 ffgg 是等价的。

【讨论】:

    猜你喜欢
    • 2012-11-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多