[swift-evolution] Type-safe selectors

Joe Groff jgroff at apple.com
Sat Dec 5 20:00:36 CST 2015

> On Dec 5, 2015, at 12:35 PM, Kevin Ballard <kevin at sb.org> wrote:
> On Sat, Dec 5, 2015, at 04:30 AM, Michel Fortin wrote:
>> Like this:
>> 	view.action = "_doSomething_UniqueSelector1234_currentModuleName_blahblah"
>> 	extension NSObject {
>> 		func _doSomething_UniqueSelector1234_currentModuleName_blahblah() {
>> 			let target = self
>> 			(target as! MyObject).doSomething()
>> 		}
>> 	}
>> (Joe Groff suggested it first.) This simply assumes the receiver will
>> derive from NSObject. You also need to set a non-nil target. And note
>> that the closure is context-free, meaning you can't capture variables
>> with it.
> How is this type-safe? You're using as! in there (and silently ignoring
> the message if the receiver is wrong wouldn't be any better). If I send
> a selector to the wrong receiver, it's still going to crash.

I think this would be better emitted like a category on MyObject than on NSObject.

> This comes back to my fundamental argument, which is that
> @convention(selector) looks like it's type-safe, but there's so many
> holes and so many implicit coercions that need to be added that you can
> drive a gigantic truck full of unsafety right through it without even
> noticing.

There's plenty of useful space between "no type safety" and "perfect type safety", IMO.


More information about the swift-evolution mailing list