title: Swift Ordered Set
body: <p>Does Swift have an <strong>ordered</strong> set type? And if not, what are my options if I want to use one?</p>
  
  <p>The standard library's <code>Set</code> is unordered, as is made clear in the documentation:</p>
  
  <blockquote>
    <p>Arrays are ordered collections of values. Sets are unordered collections of unique values. Dictionaries are unordered collections of key-value associations.</p>
  </blockquote>
  
  <p>However, many data structures suitable for implementing ordered sets (and dictionaries) are known, in particular <a href="https://en.wikipedia.org/wiki/Self-balancing_binary_search_tree" rel="noreferrer">balanced binary trees</a> such as <a href="https://en.wikipedia.org/wiki/Red%E2%80%93black_tree" rel="noreferrer">Red-Black trees</a>.</p>
  
  <p>As an example of this, c++'s stl has <a href="http://en.cppreference.com/w/cpp/container/set" rel="noreferrer">ordered sets</a> and maps, and allows range queries on them using lower and upper bounds.</p>
  
  <p>I know that a set's members can be sorted in to an array, but I am after a data structure with <code>O(log(n))</code> insertion, removal and query.</p>