user14822019
user14822019

Reputation: 25

Add last element to an array from for loop

I have a code like so...

for element in self.arr_Offline {
   self.arr_OfflineTemp.add(element)
   break
}
self.arr_Offline.removeObject(at: 0)

Here I'm looping through an array called self.arr_Offline, adding the first element from that array into another array called self.arr_OfflineTemp and immediately doing break so that the second array will have just one element and then once I'm outside the for-loop, I remove the added object from the main array by doing self.arr_Offline.removeObject(at: 0)

But I want to add the last element to self.arr_OfflineTemp instead of the first and then remove that last element from self.arr_Offline. It should look something like so...

for element in self.arr_Offline { // looping through array
   self.arr_OfflineTemp.add(lastElementOf'self.arr_Offline') //add last element
   break
}
self.arr_Offline.removeObject(at: 'last') //remove that last element that was added to `arr_OfflineTemp`

How can I achieve this..?

Upvotes: 0

Views: 312

Answers (2)

Priyanshu Tiwari
Priyanshu Tiwari

Reputation: 311

Did you try the same approach with reversed() Swift:

for i in arr.reversed():
   // your code logic

After adding element, you can remove the last element from the list using this:

lst.popLast() or lst.removeLast()

Try this for the above code:

for element in self.arr_Offline.reversed() {
   self.arr_OfflineTemp.add(element)
   break
}
self.arr_Offline.popLast()

Is this something you are looking for?

Upvotes: 0

vadian
vadian

Reputation: 285180

First of all never use NS(Mutable)Array and NS(Mutable)Dictionary in Swift.

Native Swift Array has a convenient way to do that without a loop

First element:

if !arr_Offline.isEmpty { // the check is necessary to avoid a crash
    let removedElement = self.arr_Offline.removeFirst()
    self.arr_OfflineTemp.append(removedElement)
}

Last element:

if !arr_Offline.isEmpty {
    let removedElement = self.arr_Offline.removeLast()
    self.arr_OfflineTemp.append(removedElement)
}

And please drop the unswifty snake_case names in favor of camelCase

Upvotes: 1

Related Questions