Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Swift:如何在回调闭包中使用instanceType_Swift - Fatal编程技术网

Swift:如何在回调闭包中使用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

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

如何做到这一点?

如果您可以在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的中阅读更多关于或的信息