如何传入带委托的对象

时间:2015-03-03 13:47:57

标签: ios swift uiapplicationdelegate

快速搜索这个问题什么都没给我。同时很难解释,我想这个方法都很清楚。看看这个,请:

func tap(sender: AnyObject, action: Selector) -> UITapGestureRecognizer {
        let tap = UITapGestureRecognizer(target: sender, action: action)
        tap.delegate = sender
        return tap
    }

错误:

Type 'AnyObject' does not conform to protocol 'UIGestureRecognizerDelegate'

问题是需要为AnyObject编写额外内容以避免收到此消息?还是其他任何方式?

1 个答案:

答案 0 :(得分:1)

假设sender始终属于UIGestureRecognizerDelegate类型,您可以使用强制向下转发:

tap.delegate = sender as UIGestureRecognizerDelegate

否则,请使用失败的演员:

if let delegate = sender as? UIGestureRecognizerDelegate
{
    tap.delegate = delegate
}

作为参考,请查看Swift编程语言指南中包含的Type Casting for Any and AnyObject

请注意,对我来说,这种分配委托的方式似乎很不寻常且容易出错。