Structures
The following structures are available globally.
-
A collection whose elements are key and value pairs, sorted by keys.
SortedDictionary is implemented using Red-Black Tree, so can perform insertion, search, deletion operations in logarithmic time.
Unlike Dictionary.Values, SortedDictionary.Values doesn’t conform to MutableCollection.
Example
See morelet countries = ["Singapore", "Canada", "Sweden", "Egypt", "Croatia"] var d1 = SortedDictionary(grouping: countries) { country in String(country.first!) } print(d1["C"]!) // ["Canada", "Croatia"] print(d1) // ["C": ["Canada", "Croatia"], "E": ["Egypt"], "S": ["Singapore", "Sweden"]] d1["G", default: []].append("Greece") d1["E", default: []].append("Ecuador") print(d1) // ["C": ["Canada", "Croatia"], "E": ["Egypt", "Ecuador"], "G": ["Greece"], "S": ["Singapore", "Sweden"]] let d2 = d1.compactMapValues { v in v.count > 1 ? v.map { $0.uppercased() } : nil } print(d2) // ["C": ["CANADA", "CROATIA"], "E": ["EGYPT", "ECUADOR"], "S": ["SINGAPORE", "SWEDEN"]]
Declaration
Swift
public struct SortedDictionary<Key, Value> : DictionaryCollection where Key : Comparable
-
A collection whose elements are unique and sorted.
SortedSet is implemented using Red-Black Tree, so can perform insertion, search, deletion operations in logarithmic time.
Example
See morevar s1: SortedSet = [5, 2, 3, 4] print(s1) // [2, 3, 4, 5] s1.insert(1) print(s1[s1.startIndex]) // 1 print(s1) // [1, 2, 3, 4, 5] print(s1.remove(5)!) // 5 print(s1.last!) // 4 print(s1) // [1, 2, 3, 4] let s2: SortedSet = [3, 7, 1, 9] print(s1.union(s2)) // [1, 2, 3, 4, 7, 9]
Declaration
Swift
public struct SortedSet<Element> : SetCollection where Element : Comparable