Swift Array VS. ContiguousArray

Swift is a vast language with a load of features that can be missed.

One thing I just discovered is the ContiguousArray type, As known to most of you swift uses structures for most of its data types when possible and arrays are no exception to that.

Now let’s see how swift arrays save objects in memory, And here we have two cases:
2- Value data types.
2- Classes or Objective-C protocols.

In the first case a normal array guarantees that it will always use a contiguous memory block.

The difference is that contiguous memory blocks are continuous uninterrupted blocks of memory, While non-contiguous space can be interrupted by any other object.

Contiguous Block
Non-Contiguous Block

Now in the second case (Classes or Objective-C protocols) arrays don’t make any guarantees about the way it saves data, It can save data in contiguous blocks of memory or it can save it in a non-contiguous space.

And here is where ContiguousArray comes in play, ContiguousArray always uses contiguous memory blocks regardless of the saved data types which makes it yield a bit better performance in the case of classes and Objective-C protocols.

Also a key difference between Array and ContiguousArray is that ContiguousArray does not support bridging to Objective-C code while a normal Array does.

And here is the difference between those two types of arrays, So the next time you use an array think a bit which one would be better for you. ;)

every thing.swift

Learning Swift? Me too!!

)
Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade