Here's a struct in Swift:
struct A {
var x
var y
var z
}
What should I do to get the offset of y
in the struct A
, just like offsetof(A, y)
in C?
Thanks :)
MemoryLayout.offset(of:)
was added in Swift 4.2, with the implementation of
Example:
struct A {
var x: Int8
var y: Int16
var z: Int64
}
MemoryLayout.offset(of: \A.x) // 0
MemoryLayout.offset(of: \A.y) // 2
MemoryLayout.offset(of: \A.z) // 8
Remark: This should work as well, but (as of Swift 4.2) does not compile (bug SR-8335):
MemoryLayout<A>.offset(of: \.y)
// error: Expression type 'Int?' is ambiguous without more context
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With