Difference between Array, Set and Dictionary in Swift
Asked Answered
C

4

23

I am new to Swift Lang, have seen lots of tutorials, but it's not clear – my question is what's the main difference between the Array, Set and Dictionary collection type?

Cattleya answered 19/11, 2016 at 10:58 Comment(1)
This very subject is very well covered in the Swift Language Guide - Collection Types. E.g. some highlights [emphasis mine]: "An array stores values of the same type in an ordered list" // "A set stores distinct values of the same type in a collection with no defined ordering." // "A dictionary stores associations between keys of the same type and values of the same type in a collection with no defined ordering.".Arceliaarceneaux
S
34

Here are the practical differences between the different types:

Arrays are effectively ordered lists and are used to store lists of information in cases where order is important.

For example, posts in a social network app being displayed in a tableView may be stored in an array.

Sets are different in the sense that order does not matter and these will be used in cases where order does not matter.

Sets are especially useful when you need to ensure that an item only appears once in the set.

Dictionaries are used to store key, value pairs and are used when you want to easily find a value using a key, just like in a dictionary.

For example, you could store a list of items and links to more information about these items in a dictionary.

Hope this helps :)

(For more information and to find Apple's own definitions, check out Apple's guides at https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/CollectionTypes.html)

Shantell answered 19/11, 2016 at 14:35 Comment(0)
Z
15

Detailed documentation can be found here on Apple's guide. Below are some quick definations extracted from there:

Array

An array stores values of the same type in an ordered list. The same value can appear in an array multiple times at different positions.

Set

A set stores distinct values of the same type in a collection with no defined ordering. You can use a set instead of an array when the order of items is not important, or when you need to ensure that an item only appears once.

Dictionary

A dictionary stores associations between keys of the same type and values of the same type in a collection with no defined ordering. Each value is associated with a unique key, which acts as an identifier for that value within the dictionary. Unlike items in an array, items in a dictionary do not have a specified order. You use a dictionary when you need to look up values based on their identifier, in much the same way that a real-world dictionary is used to look up the definition for a particular word.

Zeph answered 19/11, 2016 at 11:27 Comment(0)
E
10

Old thread yet worth to talk about performance.

With given N element inside an array or a dictionary it worth to consider the performance when you try to access elements or to add or to remove objects.

Arrays

To access a random element will cost you the same as accessing the first or last, as elements follow sequentially each other so they are accessed directly. They will cost you 1 cycle.

Inserting an element is costly. If you add to the beginning it will cost you 1 cycle. Inserting to the middle, the remainder needs to be shifted. It can cost you as much as N cycle in worst case (average N/2 cycles). If you append to the end and you have enough room in the array it will cost you 1 cycle. Otherwise the whole array will be copied which will cost you N cycle. This is why it is important to assign enough space to the array at the beginning of the operation.

Deleting from the beginning or the end it will cost you 1. From the middle shift operation is required. In average it is N/2.

Finding element with a given property will cost you N/2 cycle.

So be very cautious with huge arrays.

Dictionaries

While Dictionaries are disordered they can bring you some benefits here. As keys are hashed and stored in a hash table any given operation will cost you 1 cycle. Only exception can be finding an element with a given property. It can cost you N/2 cycle in the worst case. With clever design however you can assign property values as dictionary keys so the lookup will cost you 1 cycle only no matter how many elements are inside.

Expiate answered 26/5, 2017 at 18:40 Comment(1)
Thanks @Teddy, I was keen on the performance aspect and this answer ended my search. Can you please also include Sets in the comparison?Longboat
J
2

Swift Collections - Array, Dictionary, Set

Every collection is dynamic that is why it has some extra steps for expanding and collapsing. Array should allocate more memory and copy an old date into new one, Dictionary additionally should recalculate basket indexes for every object inside

Big O (O) notation describes a performance of some function

Array - ArrayList - a dynamic array of objects. It is based on usual array. It is used for task where you very often should have an access by index

get by index - O(1)
find element - O(n) - you try to find the latest element
insert/delete - O(n) - every time a tail of array is copied/pasted

Dictionary - HashTable, HashMap - saving key/value pairs. It contains a buckets/baskets(array structure, access by index) where each of them contains another structure(array list, linked list, tree). Collisions are solved by Separate chaining. The main idea is:

  1. calculate key's hash code[About] (Hashable) and based on this hash code the index of bucket is calculated(for example by using modulo(mod)).
  2. Since Hashable function returns Int it can not guarantees that two different objects will have different hash codes. More over count of basket is not equals Int.max. When we have two different objects with the same hash codes, or situation when two objects which have different hash codes are located into the same basket - it is a collision. Than is why when we know the index of basket we should check if anybody there is the same as our key, and Equatable is to the rescue. If two objects are equal the key/value object will be replaces, otherwise - new key/value object will be added inside
find element - O(1) to O(n) 
insert/delete - O(1) to O(n) 

O(n) - in case when hash code for every object is the same, that is why we have only one bucket. So hash function should evenly distributes the elements

As you see HashMap doesn't support access by index but in other cases it has better performance

Set - hash Set. Is based on HashTable without value

*Also you are able to implement a kind of Java TreeMap/TreeSet which is sorted structure but with O(log(n)) complexity to access an element

[Java Thread safe Collections]

Jacobite answered 30/11, 2021 at 22:40 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.