Archive for August 3, 2015

Monday, August 3, 2015

Swift Protocols, Arrays, and Casting

Brent Simmons (tweet):

But an EmailMessage is a NodeRepresentedObject, so it ought to work just fine.

[…]

The best way I’ve found to deal with this is to map it. […] That seems crazy. I’m using map to create an array whose members are absolutely identical to the original array.

Kevin Ballard:

It’s not a type-check. The in-memory representation is different. It has to allocate a new array with the new values.

Non-@objc protocols use a virtual function table (called a protocol witness table) rather than message-passing.

This means that objects typed as EmailMessage have a different table pointer than those typed as NodeRepresentedObject.

Brent Simmons:

I’d argue that, instead, there shouldn’t be a hidden performance gotcha.

Kevin Ballard:

That would be nice, but the only way to solve this without a new array basically requires all protocols to use message-passing

Message passing is a performance gotcha :P

Brent Simmons:

But barely. We can write fast apps in Objective-C.

Kevin Ballard:

Yeah, but you should be able to write faster ones in Swift.

Brent Simmons:

Except for when I have to make an exact copy of an array to satisfy the type system.