[swift-evolution] Type-safe selectors

Michel Fortin michel.fortin at michelf.ca
Fri Dec 4 21:03:03 CST 2015


Le 4 déc. 2015 à 21:45, Joe Groff <jgroff at apple.com> a écrit :
> 
>> - (void)action
>> - (void)action:(id)sender
>> - (void)action:(id)sender forEvent:(UIEvent *)event
> 
> Why couldn't this be covered by overloads? It's unlikely we'd be able to import selectors from Objective-C to specific types because of this and other reasons, so we'd still need an untyped Selector type, but we could easily provide well-typed overloads in Swift overlays that convert from typed selectors to untyped.

Good point. Overloads in framework overlays. That's much simpler than having the compiler trying to infer compatibility as I just suggested.


Le 4 déc. 2015 à 21:49, Brent Royal-Gordon <brent at architechies.com> a écrit :

> If you’re worried about compile-time type checking of the call site, generics can help tie the selector to the object it’s intended for:
> 
> 	func addTarget<T: NSObject>(target: T?, action: @convention(selector) T -> AnyObject -> Void, forControlEvents: UIControlEvents)

Nice.

Damned OS X with its target and action properties you have to set separately. Of course you could use the extension below, but it's still bad that you can then set the two properties separately.

	extension NSControl {
		func setTarget<T: NSObject>(target: T?, action: @convention(selector) T -> AnyObject -> Void) {
			self.target = target
			self.action = action
		}
	}


-- 
Michel Fortin
michel.fortin at michelf.ca
https://michelf.ca



More information about the swift-evolution mailing list