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)

Answer from GJZ on Stack Overflow
🌐
SwiftLee
avanderlee.com › swiftlee › swift › array vs set: fundamentals in swift explained
Array vs Set: Fundamentals in Swift explained - SwiftLee
January 26, 2024 - One practical email every Tuesday. Unsubscribe anytime. A big difference between Sets and Arrays is the uniqueness of elements. An Array can contain the same value twice while a Set will never contain duplicates.
🌐
Hacking with Swift
hackingwithswift.com › example-code › language › when-to-use-a-set-rather-than-an-array
When to use a set rather than an array - free Swift example code and tips
November 28, 2019 - You don’t care about the order of the items in the set. You don’t need to use APIs that require arrays. You’re storing Hashable types, either your own or one of Swift’s built-in types likes strings and integers.
Discussions

Difference between Array, Set and Dictionary in Swift - Stack Overflow
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? More on stackoverflow.com
🌐 stackoverflow.com
Swift - Set vs Array - Stack Overflow
On one hand I want an ordered collection, on the other hand I want every item in the collection to appear only once. I can either use an array and sort it every time I insert an item - and insert ... More on stackoverflow.com
🌐 stackoverflow.com
May 24, 2017
Swift 1.2 : What's the difference between Set and Array ?

Sets only allow unique elements in the collection.

More on reddit.com
🌐 r/iOSProgramming
9
0
February 10, 2015
More performant to filter array or set and then convert to array? (Swift) - Stack Overflow
Note that filtering is way more expensive than conversion from Set to Array. ... Sign up to request clarification or add additional context in comments. ... Just remember to benchmark using release -O (optimize for speed) Swift compiler setting 2020-08-06T15:08:06.68Z+00:00 More on stackoverflow.com
🌐 stackoverflow.com
🌐
Donny Wals
donnywals.com › how-to-decide-between-a-set-and-array-in-swift
How to decide between a Set and Array in Swift? – Donny Wals
October 2, 2024 - Arrays are meant to hold data that is ordered and this data doesn’t have to be unique · A Set in Swift holds a single type of object, just like Array does.
🌐
GeeksforGeeks
geeksforgeeks.org › swift › swift-difference-between-sets-and-arrays
Swift - Difference Between Sets and Arrays - GeeksforGeeks
November 4, 2022 - // Swift program to illustrate array // Creating and initializing an Array of String Values var arr = [ "GeeksforGeeks", "GFG", "Swift Programs" ] // Display the array print(arr) ... Set is a data structure where no duplicate elements are present. ...
🌐
Medium
medium.com › swlh › swift-array-vs-set-f2edf9e8da1d
Swift Array vs. Set: A Head-To-Head Comparison in Performance | by Yong Cui | The Startup | Medium
January 19, 2020 - As shown below, Array is a collection of ordered values, Set is a collection of unique values, while Dictionary is an unordered collection of key-value pairs. ... They are all generic data types as discussed in one of my previous Medium articles.
Top answer
1 of 4
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)

2 of 4
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.

🌐
Better Programming
betterprogramming.pub › array-vs-set-fundamentals-in-swift-explained-9c78f3552e52
Array vs Set: Fundamentals in Swift explained
August 7, 2019 - When we compare the initialization of Arrays and Sets we can see that they’re pretty similar: let arrayOfBlogCategories: [String] = ["Swift", "Debugging", "Xcode", "Workflow", "Optimization"] let setOfBlogCategories: Set<String> = ["Swift", "Debugging", "Xcode", "Workflow", "Optimization"]
Find elsewhere
🌐
Medium
medium.com › macoclock › swift-collection-types-array-vs-set-c048b0abbdd9
Swift Collection Types: Array vs Set | by Batikan Sosun | Mac O’Clock | Medium
June 22, 2020 - A Set is unordered, and each element can only appear once in a set. While an Array can contain duplicate elements, each value contained in a set is unique.
🌐
SerialCoder
serialcoder.dev › text-tutorials › swift-tutorials › arrays-vs-sets-in-swift
Arrays VS Sets In Swift – SerialCoder.dev
Since order is non-guaranteed, index-based reference of elements is actually meaningless; using an index to refer to a specific item into a Set is risky, as the order of elements can change after an addition or removal. If order of elements is important, then array is the way to go.
Top answer
1 of 1
2

There are several third-party libraries implementing an ordered set in Swift, so you could check them out.

Also, you could write your own implementation of an ordered set (you can base it on an existing one) if it is not an overkill for your task. The way you choose really depends on your app.

And in the end, you could use one of two ways that you proposed: using a built-in array or a set. In order to choose between them, take a look at your app: what action will be performed more often? Getting an access to elements in order (use array then) or addition/deletion of existing elements (probably, the set is the way to go).

This part was edited based on comments below

If you go for an array, note, that a built-in contains for arrays will not know that an array is sorted, so it will probably be O(N), not O(log(N)). So you should either write a custom replacement for the contains method, or (this is, once again probably a better way), write a custom collection class that implements contains the right way (however, since contains is a protocol extension method of SequenceType, my knowledge of Swift, I'm afraid, is not good enough yet to tell you how to do it properly, maybe someone else will).

UPDATE (based on your comment to your question):

I believe, in your particular case (a chat app) array is superior. You only have to sort old messages once, and you will not probably try to add very old messages once again, you only have to make sure you don't add new messages twice (it is implementation-dependent though, so you know better, I'm just assuming). So you only have to check that the last messages in your old array do not overlap with first messages in the array that you add. Sort of :)

🌐
YouTube
youtube.com › the dev method
Swift: Arrays vs Sets - YouTube
Learn the simple difference between sets and arrays in Swift.Mutating function link8:06:57https://www.youtube.com/watch?v=lXp3MNT_EZcSethttps://developer.app...
Published: August 9, 2020
Views: 1K
🌐
YouTube
youtube.com › sean allen
Swift Basics: Array vs. Set - YouTube
Go to https://squarespace.com/seanallen to save 10% off your first purchase of a website or domain using code SEANALLEN. Most iOS developers instinctively re...
Published: March 31, 2023
Views: 18K
🌐
Stackademic
blog.stackademic.com › swift-performance-face-off-array-vs-set-1be23a36bbcd
Swift Performance Face-off: Array vs Set | by Hugo Vanderlei | Stackademic
November 29, 2023 - Use Array when the order of elements is important or when you have many operations that depend on indexing. Use Set when order is not important, and you need fast searches, insertions, and removals.
🌐
Hacking with Swift
hackingwithswift.com › sixty › 2 › 4 › arrays-vs-sets-vs-tuples
Arrays vs sets vs tuples - a free Hacking with Swift tutorial
May 28, 2019 - let set = Set(["aardvark", "astronaut", "azalea"]) If you need a collection of values that can contain duplicates, or the order of your items matters, you should use an array: let pythons = ["Eric", "Graham", "John", "Michael", "Terry", "Terry"] Arrays are by far the most common of the three types.
🌐
Cocoacasts
cocoacasts.com › swift-fundamentals-arrays-and-sets
Arrays and Sets - Cocoacasts
January 27, 2018 - For some tasks, sets are more performant than arrays. That's something to keep in mind. Collection types are the bread and butter of the Swift developer, which means it pays to invest some time in understanding how they work and, more importantly, when to use which collection type for a particular task.
🌐
Medium
medium.com › @rashadsh › array-vs-set-in-swift-exploring-the-differences-and-best-use-cases-d04c00da5b2f
Array vs Set in Swift: Exploring the Differences and Best Use Cases | by Rashad Shirizada | Medium
July 11, 2023 - They provide random access to elements using index-based lookups, making it easy to retrieve and modify elements at specific positions. Set: A set is an unordered collection of unique elements.
🌐
Hacking with Swift
hackingwithswift.com › quick-start › understanding-swift › why-are-sets-different-from-arrays-in-swift
Why are sets different from arrays in Swift? - a free Understanding Swift tutorial
May 28, 2020 - 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 – or perhaps ...
Top answer
1 of 1
2

For just 1000 objects it shouldn't really matter.

You may try the following test (for 1 million objects):

struct Foo: Hashable {
    let id: Int
    let name: String
}

let fooArr: [Foo] = (1...1_000_000).map { Foo(id: $0, name: "hkafghhkjdsgfajhkgfkjhasdf") }
let fooSet: Set<Foo> = Set(fooArr)

let start1 = CFAbsoluteTimeGetCurrent()
let filteredArr = fooArr.filter { $0.id.isMultiple(of: 2) }
let diff1 = CFAbsoluteTimeGetCurrent() - start1
print("Array: \(diff1) seconds")
// prints "Array: 4.004199028015137 seconds"

let start2 = CFAbsoluteTimeGetCurrent()
let filteredSetToArr = Array(fooSet.filter { $0.id.isMultiple(of: 2) })
let diff2 = CFAbsoluteTimeGetCurrent() - start2
print("Set: \(diff2) seconds")
// prints "Set: 4.139569997787476 seconds"

Again there isn't much of a difference. The actual values may differ but the relative difference should be similar for every try.

I used -Ofast optimisation level.


You can even make more detailed tests:

let fooArr: [Foo] = (1...1_000_000).map { Foo(id: $0, name: "hkafghhkjdsgfajhkgfkjhasdf") }
let fooSet: Set<Foo> = Set(fooArr)

let start1 = CFAbsoluteTimeGetCurrent()
let filteredArr = fooArr.filter { $0.id.isMultiple(of: 2) }
let diff1 = CFAbsoluteTimeGetCurrent() - start1
print("Array filtering: \(diff1) seconds")

let start2 = CFAbsoluteTimeGetCurrent()
let filteredSet = Array(fooSet.filter { $0.id.isMultiple(of: 2) })
let diff2 = CFAbsoluteTimeGetCurrent() - start2
print("Set filtering: \(diff2) seconds")

let start3 = CFAbsoluteTimeGetCurrent()
let filteredSetToArr = Array(filteredSet)
let diff3 = CFAbsoluteTimeGetCurrent() - start3
print("Set to Array: \(diff3) seconds")

print("Set total: \(diff2 + diff3) seconds")

and the result will be:

Array filtering: 1.5497009754180908 seconds
Set filtering: 1.2836240530014038 seconds
Set to Array: 1.895427703857422e-05 seconds
Set total: 1.2836430072784424 seconds

Note that filtering is way more expensive than conversion from Set to Array.