Exploring Swift Array's Implementation

Jan 7, 2016
6 minute read

An (Swift) Array is contiguous block of memory which has n number of elements of same type, represented by generic type Element. Since the memory which holds the elements is contiguous any individual element can be accessed in O(1) time.

To create an array we need these things as bare minimum :

Pointer to allocated memory (or the buffer)

Capacity : capacity is the number of elements that can be stored in the current buffer

Count : count is number of elements that are actually stored inside the current buffer so count <= capacity

Swift Implementation

_SwiftArrayBodyStorage (C Struct)

Swift declares a C struct in its SwiftShim’s module inside GlobalObject.h called _SwiftArrayBodyStorage

Array (struct)

gyb stands for generate your (own) boilerplate. It’s a preprocessor system written for swift which is used to generate repetitive code.

Array is declared in a file called Arrays.swift.gyb because Array, ContiguousArray and ArraySlice share a lot of same code.

utils/gyb inside swift’s source can be used to generate the .swift file from a .gyb file

Array declares different buffer for ObjC and non ObjC runtime. _ArrayBuffer provides a bridged storage so it can be converted into NSArray if needed. We’re focusing on above mentioned _ContiguousArrayBuffer.

publicsubscript(index:Int)->Element{get{// This call may be hoisted or eliminated by the optimizer. If// there is an inout violation, this value may be stale so needs to be// checked again below.letwasNativeTypeChecked=_hoistableIsNativeTypeChecked()// Make sure the index is in range and wasNativeTypeChecked is// still valid.lettoken=_checkSubscript(index,wasNativeTypeChecked:wasNativeTypeChecked)return_getElement(index,wasNativeTypeChecked:wasNativeTypeChecked,matchingSubscriptCheck:token)}mutableAddressWithPinnedNativeOwner{_makeMutableAndUniqueOrPinned()_checkSubscript_native(index)return(_getElementAddress(index),Builtin.tryPin(_getOwner_native()))}}