As Set is "An unordered collection of unique elements.", the "first" element is kind of random. So, what is the difference between the functions randomElement and first ?
As Set is "An unordered collection of unique elements.", the "first" element is kind of random. So, what is the difference between the functions randomElement and first ?
While the interface of Set is an unordered collection, internally it has an order that depends on its implementation. This is partially because you cant store anything on a computer truly unordered. It is also because Set conforms to Collection, it has the following property
Iterating over the elements of a collection by their positions yields the same elements in the same order as iterating over that collection using its iterator.
That means that it needs to have some kind of internal ordering to allow the consistency between different methods of iterating.
So while it's defined what value you'll get back from first, it will be consistent until a value is inserted or removed from the Set. randomElement will always return a randomly chosen element independent of what the underlying order is.
In this case, The main difference is getting the first element of a certain set you will always get the same value for the same execution. On the other hand, randomElement should return "random" element.
"same execution" means that the set should keep the same elements sorting once it's declared, however, if somehow the set declaring is re-executed, it might have a different sort. Example:
let mySet: Set<Int> = [1, 2, 3, 4, 5]
print(mySet) // let's consider it's: [5, 1, 2, 3, 4]
At this point, the sort of elements should be the same each time iterate through it; first should always give 5 in this case, but randomElement should give a random integer from 1 to 5. When the code for declaring mySet is re-executed, it might have a different sort, but it will keep returning the same first element.
As an example of re-executing the code, working with an iOS app and declared a set in a certain view controller, each popping/pushing from/to the navigation stack should cause declaring the set to be executed.