How to remove every element in an array in Swift?

So I have an array:

var stringArray = ["a","b","c","d","e","f","g","h","i","j"] 

Now, how do I remove "a", "c", "e", "g" and "i" (all indices of an even number from an array)?

Thanks!

+5
source share
3 answers

Instead of using C-style for-loops (which are deprecated in the upcoming version of Swift), you can accomplish this with the steps:

 var result = [String]() for i in 1.stride(to: stringArray.count, by: 2) { result.append(stringArray[i]) } 

Or for an even more functional solution,

 let result = 1.stride(to: stringArray.count, by: 2).map { stringArray[$0] } 
+12
source

Traditional

 var filteredArray = [] for var i = 1; i < stringArray.count; i = i + 2 { filteredArray.append(stringArray[i]) } 

Functional Alternative

 var result = stringArray.enumerate().filter({ index, _ in index % 2 != 0 }).map { $0.1 } 

enumerate takes an array of elements and returns an array of tuples, where each tuple is a pair of indexed arrays (for example, (.0 3, .1 "d") ). Then we remove the elements that are odd using the module operator. Finally, we convert the tuple array back to a regular array using map . NTN

+6
source

There are several ways to do this, but here are a couple that seemed interesting to me:

Using flatMap() on indices :

 let result: [String] = stringArray.indices.flatMap { if $0 % 2 != 0 { return stringArray[$0] } else { return nil } } 

Note. result must be defined as [String] , otherwise the compiler does not know which version of flatMap() use.

Or, if you want to change the original array in place:

 stringArray.indices.reverse().forEach { if $0 % 2 == 0 { stringArray.removeAtIndex($0) } } 

In this case, you must first call reverse() on indices so that they are listed in reverse order. Otherwise, by the time you get to the end of the array, you will try to remove the index that no longer exists.

+2
source

Source: https://habr.com/ru/post/1244986/


All Articles