0

I want to pass self as instancetype to the callback closure of this function:

extension UIView {
    public func onTap(_ handler: @escaping (_ gesture: UITapGestureRecognizer, _ view: Self) -> Void) -> UITapGestureRecognizer {
        ...
    }
}

let view = UIView.init()
view.onTap { tap, v in
    ...
}

But I got an error:

Self' is only available in a protocol or as the result of a method in a class; did you mean 'UIView'?

How can I do this?

0

1 Answer 1

1

that is just the perfect scenario (by book) when you can use protocols and extensions in Swift quite efficiently:

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 { }

then for e.g.:

let button = UIButton.init()
button.onTap { tap, v in
    // v is UIButton...
}

while for e.g.:

let label = UILabel.init()
label.onTap { tap, v in
    // v is UILabel...
}

etc...


NOTE: you can read more about Extensions or the Protocols in the Swift Programming Language Book from Apple.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.