Venkat Venkat - 1 year ago 91
Swift Question

Identify the completion of for loop in swift

i am having the following for loop,

for (key, value) in changedDataDictionary {
// here i want to identify last key and value

I want to identify the execution of last object/ completion of the for loop

It may be very silly question, but i dont have any idea about that.
Thanks in advance.

Answer Source

This will work in general

var index: Int = 0

for (key, value) in changedDataDictionary {
   index += 1;
   if (index == changedDataDictionary.count) {
      // do something

Note that a dictionary doesn't have a defined order so the last element will always be a different one and usually there is a better solution than using a tracking index.

If you just want to identify last key and element, you can also:

var lastKey: KeyType? = nil
var lastElement ValueType? = nil

for (key, value) in changedDataDictionary {
   lastKey = key;
   lastValue = value;

// do something with last key and value
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download