Index(before:) with sets/dictionaries

let words: Set = ["apple", "banana", "cherry"]

let beforeEnd = words.index(before: words.endIndex)

print(words[beforeEnd])  // Output: One of the elements (order not guaranteed)




let prices = ["milk": 1.99, "bread": 2.49]

let last = prices.index(before: prices.endIndex)

let entry = prices[last]

print("\(entry.key): \(entry.value)")

Works with Arrays, but not Sets/Dictionaries. Is this expected?

I guess you mean by "works" with Arrays that the order is guaranteed?
If so, it is expected that Set/Dictionary don't guarantee the order.
If you need that you can use OrderedSet/OrderedDictionary from swift-collections.

1 Like

I get compiler errors.

I guess the problem is that sets and dictionaries are not bidirectional collections.

Ah I see. And yes that is correct.

1 Like