[swift-evolution] [Pitch] Reducing the bridging magic in dynamic casts

Joe Groff jgroff at apple.com
Mon May 2 17:43:08 CDT 2016

> On May 2, 2016, at 2:45 PM, Chris Lattner <clattner at apple.com> wrote:
> On Apr 29, 2016, at 3:00 PM, Joe Groff via swift-evolution <swift-evolution at swift.org> wrote:
>> I’d like to propose the following changes:
>> 	• Dynamic casts as?, as! and is should no longer perform bridging conversions between value types and Cocoa classes.
>> 	• Coercion syntax as should no longer be used to explicitly force certain bridging conversions.
>> 	• To replace this functionality, we should add initializers to bridged value types and classes that perform the value-preserving bridging operations.
> +1.  I think that this will lead to a much cleaner and more predictable set of rules.  It will probably also define away a ton of bugs in the compiler and runtime.
>> NSError bridging can also be extracted from the runtime, and the same functionality exposed as a factory initializer on NSError:
> I think that this proposal is overall really great, but what does it do to the “catch let x as NSError” pattern?  What is the replacement?  If the result is ugly, we may have to subset out NSError out of this pass, and handle it specifically with improvements to the error bridging story.

If we remove the bridging magic and do nothing else, then the best you can do to catch any error and handle it as an NSError becomes a two-liner:

	do {
	  try something()
	} catch let error {
	  let nsError = NSError(error)

That's definitely uglier, but just to play devil's advocate, this does have the benefit of making it much clearer that the 'catch' is exhaustive. 'as' patterns are usually refutable, and it's a weird exception that 'error as NSError' is an exhaustive match (and we do have bugs where we get this wrong, especially inside closures when we haven't fully propagated contextual types yet).


More information about the swift-evolution mailing list