[swift-evolution] [Idea] Expression to retrieve the Objective-C selector of a method

Douglas Gregor dgregor at apple.com
Sun Dec 27 01:48:04 CST 2015


Hi all,

Currently, producing an Objective-C selector in Swift is an error-prone operation. One effectively just writes a string literal and uses it in a context where an ObjectiveC.Selector is expected:

	control.sendAction(“doSomething:”, to: target, forEvent: event)

There are many points of failure here:

1) The compiler doesn’t syntax-check at all to make sure it’s a valid spelling for a selector
2) The compiler doesn’t look for existing methods with this selector anywhere
3) The mapping from a Swift method name to an Objective-C selector isn’t always immediately obvious (especially for initializers), and will be getting significantly more complicated with the renaming work for Swift 3 (https://github.com/apple/swift-evolution/blob/master/proposals/0005-objective-c-name-translation.md).

I suggest that we add an expression ‘objc_selector(method-reference)` that produces the Objective-C selector for the named method, and produces an error if the method does not have an Objective-C entry point. For example:

	control.sendAction(objc_selector(MyApplication.doSomething), to: target, forEvent: event)

“doSomething” is a method of MyApplication, which might even have a completely-unrelated name in Objective-C:

	extension MyApplication {
		@objc(jumpUpAndDown:)
		func doSomething(sender: AnyObject?) { … }
	}

By naming the Swift method and having objc_selector do the work to form the Objective-C selector, we free the programming from having to do the naming translation manually and get static checking that the method exists and is exposed to Objective-C.

This proposal composes with my “Generalized Naming for Any Function” proposal, which lets us name methods fully, including getters/setters:

	let sel1: Selector = objc_selector(UIView.`insertSubview(_:at:)`) // produces the Selector “insertSubview:atIndex:"
	let sel2: Selector = objc_selector(UIView.`frame.get`) // produces the Selector “frame"

I don’t like the `objc_selector` syntax at all, but otherwise I think this functionality is straightforward.

	- Doug



More information about the swift-evolution mailing list