How to get last entered value in a Dictionary in Swift?

3 Solutions Collect From Internet About “How to get last entered value in a Dictionary in Swift?”

What you are after is generally known as a Ordered Dictionary, i.e. a dictionary that remembers the order that items have been added. A quick Google search turns up a GitHub project that may suit you.

https://github.com/lukaskubanek/OrderedDictionary

With this as the type of your dictionary, you could just use:

dictionary.last // returns Optional(("CCC", "333"))

The GitHub page has details on how you would go about adding this class to your project.

If your key is sorted you can try:

var dictionary = Dictionary<String, String>()
dictionary.updateValue("AAA", forKey: "111")
dictionary.updateValue("BBB", forKey: "222")
dictionary.updateValue("CCC", forKey: "333")

print(dictionary.keys.sorted().last.map({ ($0, dictionary[$0]!) }))

The whole point of dictionaries is they’re NOT ordered. This is why their lookups are generally so fast is because they partition elements without regard for their order.

If you want items in a particular order, you should use an array. Yes, “sorted dictionaries” exist, but they’re really just dictionary-like interfaces on top of arrays. They contain none of the benefits that traditional dictionaries bring.

If you think you need an ordered dictionary, you probably need to consider a new structure for your data.