Swift:如何在回调闭包中使用instanceType

时间:2018-02-01 09:56:26

标签: swift

我想将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'?

我该怎么做?

1 个答案:

答案 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中详细了解ProtocolsSwift Programming Language Book。< / em>的