Swift:如何在回调闭包中使用instanceType
我想将self作为instancetype传递给此函数的回调闭包:Swift:如何在回调闭包中使用instanceType,swift,Swift,我想将self作为instancetype传递给此函数的回调闭包: extension UIView { public func onTap(_ handler: @escaping (_ gesture: UITapGestureRecognizer, _ view: Self) -> Void) -> UITapGestureRecognizer { ... } } let view = UIView.init() view.onTap { ta
extension UIView {
public func onTap(_ handler: @escaping (_ gesture: UITapGestureRecognizer, _ view: Self) -> Void) -> UITapGestureRecognizer {
...
}
}
let view = UIView.init()
view.onTap { tap, v in
...
}
但我有一个错误:
Self' is only available in a protocol or as the result of a method in a class; did you mean 'UIView'?
如何做到这一点?如果您可以在Swift中非常有效地使用协议和扩展,这正是书本上的完美场景:
protocol Tappable { }
extension Tappable { // or alternatively: extension Tappable where Self: UIView {
func onTap(_ handler: @escaping (UITapGestureRecognizer, Self) -> Void) -> UITapGestureRecognizer {
return UITapGestureRecognizer() // as default to make this snippet sane
}
}
extension UIView: Tappable { }
然后,例如:
let button = UIButton.init()
button.onTap { tap, v in
// v is UIButton...
}
let label = UILabel.init()
label.onTap { tap, v in
// v is UILabel...
}
而对于例如:
let button = UIButton.init()
button.onTap { tap, v in
// v is UIButton...
}
let label = UILabel.init()
label.onTap { tap, v in
// v is UILabel...
}
等等
注意:您可以在Apple的中阅读更多关于或的信息