[swift-evolution] MemoryLayout for a value

Adrian Zubarev adrian.zubarev at devandartist.com
Sat Aug 6 04:05:32 CDT 2016


What’s so confusing about MemoryLayout<T.Type>.size?

size in this context gives you the size for the metatype of T, not the size of T.

If I memorize correctly:

Size of metatypes of value types and functions/closures is 0.
Size for class metatypes is 8.
Size for protocols metatypes (in your case it’s P.Protocol, not P.Type) is 16 except for the (old) empty protocol Any which is 8.
You may ask why these metatypes have these sizes?! I can’t answer this question, because I don’t know the technical reason, but it doesn’t matter in our case.

Furthermore there is a difference between T.Type and what you get from T.self.

T.self returns a concrete metatype for T. T.Type is a metatype supertype for all subtypes of T if there exist a subtype relationship.

That’s why something like this works fine:

let a1: Any.Type = Int.self // `Int.self` is 0 where `Any.self` is 8
let a2: Any.Type = P.self // same story with different sizes
We’re revising our proposal to provide a clear distinction of this behavior and get rid of .Protocol and .Type.



-- 
Adrian Zubarev
Sent with Airmail

Am 6. August 2016 um 04:35:50, Boris Wang via swift-evolution (swift-evolution at swift.org) schrieb:

codes in swift REPL:

protocol P {
var x:Int {get}
}
MemoryLayout<P>.size
//r0 : Int = 40

struct S1 {
var v1:Int = 0
}
MemoryLayout<S1>.size
//r1: Int =8

struct S2: P {
var v2: Int
var x:Int
}
MemoryLayout <S2>.size
//r2: Int = 16

** Question:
Why we need to known the size of a object that can't be instanced?

** Confuse:
MemoryLayout <S2.Type>.size
//r3: Int = 0

MemoryLayout <P.Type>.size
//r4: Int = 16
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20160806/03af79b3/attachment.html>


More information about the swift-evolution mailing list