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.
source share