0

I have a swift Array that I populate a UITableview with.

e.g

var array: Array<String> = ["ExampleString1","ExampleString2","ExampleString3"]

My question is how to do append all items that come after the Indexpath.row I press to a new array.

e.g I press the the first UITableview cell which is row 0 and in didSelectItemAtIndexPath I can pick up the indexpath

let test = array[indexPath.row]

If I pressed the first cell I want to add ExampleString2 and ExampleString3 by appending to my new array

var newArray: Array<String> = []
newArray.append(Everything After Indexpath that was pressed.)
1
  • Use a for loop, starting at indexPath.row+1 up to array.count-1 Commented Jan 28, 2016 at 5:56

1 Answer 1

1
var array = ["ExampleString1", "ExampleString2", "ExampleString3"]
let indexPath = 0 // Your indexPath

let newArray = array.enumerate().filter { $0.index > indexPath }.map { $0.element }

Something like this.

And using Paulw11's suggestion: (if he posts his answer I'll delete mine)

var newArray: [String] = []

for index in indexPath + 1...array.count - 1 {
    newArray += [array[index]]
}

Another variation based on Paulw11's suggestion:

let newArray = array[indexPath + 1...array.count - 1].map { $0 }

Or:

let newArray = Array(array[indexPath + 1...array.count - 1])

They all print out:

print(newArray) // ["ExampleString2", "ExampleString3"]

You'll have to add some safety checks because the way it is right now will cause an error if your indexPath.row is the last element. In that case, my original answer (the first one) is more safe.

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

1 Comment

Thanks This is exactly what what I needed. Much appreciated.

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.