Difference between Sets and Arrays in swift

Pratima S
Feb 21, 2021
  • Both sets and arrays are collections of data, meaning that they hold multiple values inside a single variable
  • sets are unordered and cannot contain duplicates, whereas arrays retain their order and can contain duplicates.

because sets don’t need to store your objects in the order you add them, they can instead store them in a seemingly random order that optimizes them for fast retrieval. So, when you say “does this set contain item X,” you’ll get an answer in a split second no matter how big the set is.

In comparison, arrays must store their items in the order you give them, so to check whether item X exists in an array containing 10,000 items Swift needs to start at the first item and check every single item until it’s found

--

--