我有一个向上冒泡的扩展,
但是在 Swift 3 中,
Generic parameter 'T' could not be inferred
public extension UIResponder
{
public func next<T>() -> T?
{
guard let responder = self.next
else { return nil }
return (responder as? T) ?? responder.next()
}
}
// note - kudos to this excellent post:
// https://blog.veloxdb.com/2016/05/12/bubbling-events-using-uiresponder-in-swift/
在 Swift<3 中,您可以像这样使用它:
class SnapDot:UIView
{
.....
func handleTap(g:UITapGestureRecognizer)
{
(next() as Snap?)?.oneDotWasClicked(self)
}
我担心不仅(a)我不明白为什么它不会在 Swift 3 中推断出来,而且(b)即使通过无休止地尝试随机变化,我也无法让它在 Swift 中工作3:O
最佳答案
这是 UIResponder
的现有 next
方法与您的扩展方法之间的名称冲突。里面的self.next
您的方法指的是(通用)方法本身。
重命名扩展使其编译:
public extension UIResponder {
public func nextOfType<T>() -> T? {
guard let responder = self.next
else { return nil }
return (responder as? T) ?? responder.nextOfType()
}
}
即使你没有要求,这里也是一个迭代而不是 递归版本:)
public extension UIResponder {
public func nextOfType<T>() -> T? {
var current = self
while let responder = current.next {
if let match = responder as? T {
return match
}
current = responder
}
return nil
}
}
关于generics - Swift 3 需要更多信息来推断参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39835937/