What is a selector, how does #selector map Swift names to it, and what does the colon count mean?
Predict first
What selector name does Swift generate?
print(NSStringFromSelector(#selector(NSString.substring(from:))))
- substring:from:
- substringFromIndex:
- substring(from:)
Predict first
What selector name does Swift generate?
print(NSStringFromSelector(#selector(NSMutableString.insert(_:at:))))
- insertString:atIndex:
- insert:at:
- insert_at
Mental model. A selector is the label on a button, such as “open door”. It does not say whose door it is; each object decides what the button does.
A selector (SEL) is the runtime’s name for a message: an interned string such as insertString:atIndex:. Its colons give the argument count, and the argument labels are folded into the name, so doThing, doThing: and doThing:with: are three different selectors. Selectors do not include types or the class, so two unrelated classes can implement the same selector.
In Swift, write #selector(Class.method(_:)) and the compiler checks the method exists, is exposed with @objc, and translates the Swift name to its Objective-C selector: substring(from:) becomes substringFromIndex:. The string form Selector("name:") skips every check, so a typo is a runtime crash. Use #selector for target-action, perform and notification handlers, and prefer closures where the API allows.
The Objective-C method is substringFromIndex:. Swift’s import renames it, and #selector maps back.
The argument labels become part of the name, and the colons count the arguments: two arguments, two colons.
Common traps
- Hand-typing selector strings. A wrong colon count compiles and crashes later.
- Forgetting
@objcon the target method.#selectorrefuses to compile without it.
They might follow up with
- What does
#selector(getter:)do? It names a property’s getter selector, as#selector(getter: NSString.length). - Why avoid
perform(_:)in new code? It returns an unmanaged object and gives up type checking. Closures or protocols are safer.
Related questions
- 4.1.1 What happens when you send a message in Objective-C, and what if nothing responds?
- 4.4.1 What do @objc, @objcMembers, @objc(name), dynamic and @nonobjc each do?
← What happens when you send a message in Objective-C, and what if… What are the stages of message forwarding, and when would you use… →