1

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?

  • 1
    This has to do with legacy code and Objective-C. The API was designed when there was Objective-C and it uses message sending paradigm. ``objc_msgSend```. – kandelvijaya Aug 16 '16 at 09:46

3 Answers3

2

#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 Objective-C selector strings.

You can't 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.

Bhaumik Surani
  • 1,730
  • 3
  • 19
  • 40
Daniel Sumara
  • 2,234
  • 20
  • 25
  • You can bypass class name only if you declare `Selector` for method existed in `self`. – Yury Aug 16 '16 at 10:19
0

From UIGestureRecognizer doc:

public init(target: AnyObject?, action: Selector) // designated initializer

So It's clear that action will be Selector type thats why you have to write #selector(SomeClass.someFunction)

Dharmesh Kheni
  • 71,228
  • 33
  • 160
  • 165
0

To tackle simple typos that could easily introduce bugs, Swift 2.2 deprecates using strings for selectors and instead introduces new syntax: #selector.

See:- https://swift.org/blog/swift-2-2-new-features/ (Compile-time checked selectors)

Dravidian
  • 9,945
  • 3
  • 34
  • 74