[swift-evolution] MemoryLayout for a value
Dave Abrahams
dabrahams at apple.com
Thu Aug 4 18:02:16 CDT 2016
on Thu Aug 04 2016, Dmitri Gribenko <gribozavr-AT-gmail.com> wrote:
> 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.
>
> Dmitri
Okay, I'm convinced; that's what we should do.
--
-Dave
More information about the swift-evolution
mailing list