Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift Ordered Set

Tags:

swift

set

Does Swift have an ordered set type? And if not, what are my options if I want to use one?

The standard library's Set is unordered, as is made clear in the documentation:

Arrays are ordered collections of values. Sets are unordered collections of unique values. Dictionaries are unordered collections of key-value associations.

However, many data structures suitable for implementing ordered sets (and dictionaries) are known, in particular balanced binary trees such as Red-Black trees.

As an example of this, c++'s stl has ordered sets and maps, and allows range queries on them using lower and upper bounds.

I know that a set's members can be sorted in to an array, but I am after a data structure with O(log(n)) insertion, removal and query.

like image 385
Benjohn Avatar asked Oct 02 '17 21:10

Benjohn


People also ask

Are Swift sets ordered?

At the time being there is no ordered set in Swift. Despite using NSOrderedSet on all Apple platforms, you can simply combine a Set with an Array to basically get the same effect. The Set is used to avoid duplicate entries, the Array is used to store the order.

What is ordered set in mathematics?

An ordered set is a relational structure (S,⪯) such that the relation ⪯ is an ordering. Such a structure may be: A partially ordered set (poset) A totally ordered set (toset) A well-ordered set (woset)

What is a Swift collection?

Swift provides three primary collection types, known as arrays, sets, and dictionaries, for storing collections of values. Arrays are ordered collections of values. Sets are unordered collections of unique values. Dictionaries are unordered collections of key-value associations.

How do I get an ordered set in Python?

The simplest way to create an ordered set in Python is to use the OrderedSet class. Note that this class is not included by default. You first need to make sure you have the ordered-set package installed. This will enable you to use the OrderedSet class.


2 Answers

Swift does not have a native ordered set type. If you use Foundation, you can use NSOrderedSet in Swift. If not, you have the opportunity to write your own ordered set data structure.

Update: Swift Package Manager includes an OrderedSet implementation that may be useful. It wraps both an array and a set and manages access to get ordered set behavior.

Update #2: Apple's Swift Collections repository contains an ordered set implementation.

like image 200
Tom Harrington Avatar answered Oct 01 '22 18:10

Tom Harrington


On April 6th, 2021, a new package of Swift was released: Swift-Collection where three more data structures have been implemented. (OrderedSet, OrderedDictionary, Deque)

However, this package is in its pre-1.0 release state. As a result, it might not be stable.

Swift blog: Release of Swift Collections

like image 42
Yan Zhuang Avatar answered Oct 01 '22 20:10

Yan Zhuang