Data Structure in Swift (Array & Dictionary) — Part 1

In this story, we will learn about the basic data structures in the Swift language i.e. Array and Dictionary and will cover the things only will be required to move on to learn Data Structure.

Nitin Aggarwal
3 min readJan 29, 2020

Array

struct Array<Element>

An ordered and indexed collection of values.

  • An array is a generic collection in Swift means you can store the data of any type. See below example:
  • An array is a Sequence which means you can iterate an array using any loop. See below example:
  • An array is a collection which means you can traverse, also it can be accessed using s subscript operator i.e. let name = names[0]. See below example:
  • An array is a RandomAccessCollection(Protocol) which means it guarantees efficiency. Like ‘count’ property always take the same time to given the size of that array whatever the size of an array.
  • Insertion Location: Inserting an element at the last of the array is the most efficient way to insert an element. It’s a constant time operation i.e. O(1). Inserting an element at a particular position may be time taken i.e. O(n).
  • Copy Behaviour: As Swift’s Array is a structure type. This means that the array is copied when they are assigned to other variables or constant or passed to a function. See below example:

Dictionary

struct Dictionary<Key, Value> where Key : Hashable

An unordered collection of key-value pairs.

  • It does not have any guarantees of order. See below example:
  • While inserting an element, the order will be the same every time until the collection is changed or mutated. See below example:

If you will see the above example, the dictionary’s order is changing after the dictionary has modified before that order is the same.

  • It does not worry about elements shifting around, the time complexity will be always O(1).
  • Searching a particular element in Dictionary is also done in O(1) which is faster than the O(n) searching time in Array.

In the next article, we will learn about Linked List in Swift.

If you have enjoyed it, clap it 🤲

Don’t forget to look into my previous stories:

Happy Coding !!

Nitin A

--

--

Nitin Aggarwal

Lead Software Engineer (iOS), Technical Writer, Technical Interviewer, Helping you to crack your iOS interview.