我想将self
作为instancetype
传递给此函数的回调闭包:
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'?
我该怎么做?
答案 0 :(得分:1)
这可以非常有效地在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...
}
等...
注: 您可以在Apple的Extensions中详细了解Protocols或Swift Programming Language Book。< / em>的