Junior — Middle
How to implement storage of elements in a set with order support?
sobes.tech AI
Answer from AI
To store elements in a set while preserving the order of insertion in iOS (Swift), you can use a data structure that combines the properties of a set and an array. Starting from iOS 13 and macOS 10.15, Swift's standard library includes the OrderedSet type, which does exactly that — it stores unique elements and maintains their order.
Example of using OrderedSet:
import Foundation
var orderedSet = OrderedSet<String>()
orderedSet.append("apple")
orderedSet.append("banana")
orderedSet.append("apple") // will not be added again
print(orderedSet) // ["apple", "banana"]
If OrderedSet is not available, you can implement similar behavior using an array for order and a set for checking uniqueness:
var array: [String] = []
var set: Set<String> = []
func addElement(_ element: String) {
if !set.contains(element) {
set.insert(element)
array.append(element)
}
}
addElement("apple")
addElement("banana")
addElement("apple")
print(array) // ["apple", "banana"]
This way, you preserve the insertion order and element uniqueness.