tucan9389
tucan9389

Reputation: 168

What is the difference between Swift structs and Objective-C structs?

In my first job interview, I was asked what is the difference between Swift structs and Objective-C structs.

Can anybody explain this difference in depth? Any help would be appreciated.

Upvotes: 2

Views: 1924

Answers (1)

Rob Napier
Rob Napier

Reputation: 299345

An Objective-C struct is a C struct, and a C struct is just a block of memory with offsets defined by the struct properties. So, if a struct has three int properties, x, y, z, we know that x is just an alias for "the beginning of the structure," y is just an alias for "this many bytes after the beginning of the structure," and z is just an alias for "some other number of bytes after the beginning of the structure." A C struct could be stored on the stack if it's a local (automatic) variable, or could be stored on the heap by calling malloc and using a struct pointer to reference that memory. A C struct is a very primitive type. And again, ObjC structs are just C structs. There's no difference. (In fact, that's why you can't put ARC-managed objects into a struct; they're just C structs, and ARC can't deal with that.)

Swift structs are a completely different beast. They are generally still implemented as a block of memory, either on the stack or on the heap that has properties that are offsets into the memory block, but that's mostly just an implementation detail. Swift structs are rich types that can have methods, extensions, conform to protocols, and most other things one might expect of an advanced type in a type-rich language.

Most importantly, Swift structs are not just "memory puns" like C structs. You can point different C structs at the same memory, and read it different ways (unions of course can do that, but you can also just do it with structs directly). There's no rule that the underlying memory block be the same size as the struct in C (this is how objc_object works, for example). But Swift structs don't allow that kind of memory aliasing. They "own" their memory much more directly. If you want to mess around with their internal memory, you have to go through some kind of "unsafe" interface. You can't just add 4 to a pointer and grab whatever value is there like a C struct.

Because of all this, you can store ARC-managed objects in a Swift struct (and in fact this is done all the time in stdlib.)

So yeah, completely different critters, despite having the same name. The one thing that is really the same is they're both value types with properties.

Upvotes: 13

Related Questions