0

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..?

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

Comments

0

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?

4 Comments

ok @Priyanshu Tiwari. so you mean I can do for element in self.arr_Offline.reversed { .. }..but how do I do lst.pop() or del lst[-1]..?..
there is no method called pop in swift
use popLast() or removeLast()
for element in self.arr_Offline.reversed() { self.arr_OfflineTemp.add(element) break } self.arr_Offline.popLast()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.