Exploring Swift Array’s Implementation
Swift declares a C struct in its SwiftShim’s module inside GlobalObject.h called
_SwiftArrayBodyStorage
[…]
count
is the number of elements currently stored in the buffer
_capacityAndFlags
is used to store two things:
- first is the capacity of the buffer
- second “Is the Element type bitwise-compatible with some Objective-C class?”
Via David Smith:
Apparently C-like performance, memory safety, resizing, copy-on-write, and ObjC bridging all together is hard
The subscript
implementation in _ContiguousArrayBuffer
has an interesting note:
Manually swap because it makes the ARC optimizer happy.
The method is also marked with a mysterious nonmutating
keyword, which the Swift language guide mentions but does not explain. This could be an optimization to avoid unnecessary writebacks or a way to make the compiler enforce that the setter does not actually change any properties of the structure (just the contents of the memory they point to).
Update (2016-05-03): Jasdev Singh:
Stepping through Sidney’s example, we can see how
nonmutating
signals that a setter doesn’t modify the containing instance, but instead has global side effects.