[swift-evolution] MemoryLayout for a value

Dmitri Gribenko gribozavr at gmail.com
Thu Aug 4 17:20:24 CDT 2016

On Wed, Aug 3, 2016 at 7:28 PM, Xiaodi Wu via swift-evolution
<swift-evolution at swift.org> wrote:
> Could I suggest an alternative? It's conservative in that it mimics the
> relationships we had before the proposal was implemented and also maintains
> the simplicity of the caseless enum:
> ```
> extension MemoryLayout {
>   static func size(ofValue _: T) -> Int { return MemoryLayout.size }
>   // etc.
> }
> ```

I like this API.  I think given all the alternatives that we explored,
it is better than those.  I also think that it nicely avoids the
following issue with the proposed MemoryLayout.of(type(of:
someExpression)).size syntax.

Imagine that you have a value whose static type differs from the
dynamic type.  For example, a protocol existential:

protocol P {}
extension Int : P {}
var x: P = 10

The question is, what does MemoryLayout.of(type(of: x)).size compute,
size of the existential box, or the size of an Int instance?  The
semantics of 'type(of:)' are "return the dynamic type", so the
straightforward conclusion is that MemoryLayout.of(type(of: x)).size
returns the size of the dynamic type instance, of Int.

What actually happens is that 'type(of: x)' returns a dynamic value of
'Int.self', statically typed as 'P.Type'.  So P gets deduced for the
generic parameter of MemoryLayout, and MemoryLayout.of(type(of:
x)).size returns the size of the protocol box.

I think due to this complex interaction, using type(of:) might lead to
confusing code, and thus I like Xiaodi's approach better.


(j){printf("%d\n",i);}}} /*Dmitri Gribenko <gribozavr at gmail.com>*/

More information about the swift-evolution mailing list