I want to remove an element within a for-in loop if it fails a certain condition. Currently, there's a solution here, but it's old and seems complicated for all I'm trying to do.
In Java, I can just reference the index like so:
/* Program that removes negative numbers from an array */
//Make an array list and add some numbers to it.
ArrayList<Int> a = new ArrayList<Int>;
for (int i = 0; i < 10; i++){
a.add( (int) ((Math.random - 0.5) * 100) //Add 10 numbers that are pos/neg.
//Remove all the negative numbers.
for (int i = 0; i < a.size; i++){
if (a.get(i) < 0){
a.remove(i); //Removes the element.
}
}
But in Swift, to my understanding, I have to use a for-each loop equivalent:
var array = [-4, -2, 0, 4, 6, 7, 2, 5, 7]
//Iterate looking for numbers < 0.
for item in array{
if (item < 0){
array.removeAt(item) //ERROR
}
else{
//Right now, I just copy every value into a new array.
//But I shouldn't even need this w/ the Arrays collection.
}
How can I do this more simply? Sorry I'm a newbie here; thanks for your help!
Edit | Clarification June 14, 2020 at 11:44 PM:
Someone suggested filter which is a stellar response, but not what I was looking for. (My bad, sorry). I used this as an example for a different challenge I'm working on here while I learn Swift.
Please help me look for solutions that remove an element. Thank you!!