Daniel with a Spaniel Daniel with a Spaniel - 3 months ago 17
Swift Question

When creating a UIGestureRecognizer, why does its action use a #selector?

Take this code, for example.

let swipe = UISwipeGestureRecognizer(
target: self, action: #selector(SomeClass.someFunction)


Why is the action
#selector(MyClass.function)
? Why can't it just be
MyClass.function
without the selector wrapping?

Answer

#selector is just wrapper on function that check syntactics. It test only if method you declare exist in your code. This way you will avoid errors like typo in objectiv-c selectors strings.

You cannot pass pointer to func as you suggest because under hood selectors works in little other way then call method.

I think it works like perform selector on target, not simply invoke selector method.

You can avoid using class name in #selector. Pass #selector(yourMethod) or #selector(yourMethodWithParam(_:)) is also valid.