8

So say I have an array:

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

Now, how do I delete "a", "c", "e", "g", and "i" (all the even number indexes from the array)?

Thanks!

4 Answers 4

17

Instead of using C-style for-loops (which are set to be deprecated in an upcoming version of Swift), you could accomplish this using strides:

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

Or for an even more functional solution,

let result = stride(from: 1, to: stringArray.count - 1, by: 2).map { stringArray[$0] }
Sign up to request clarification or add additional context in comments.

2 Comments

Value of type 'Int' has no member 'stride'
It's a global function now. See documentation here: developer.apple.com/documentation/swift/1641347-stride. The code should look something like this instead: let result = stride(from: 1, through: stringArray.count - 1, by: 2).map { stringArray[$0] }
10

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 a array of elements and returns an array of tuples where each tuple is an index-array pair (e.g. (.0 3, .1 "d")). We then remove the elements that are odd using the modulus operator. Finally, we convert the tuple array back to a normal array using map. HTH

Comments

3

There are a bunch of different ways to accomplish this, but here are a couple that I found interesting:

Using flatMap() on indices:

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

Note: result needs to be defined as a [String] otherwise the compiler doesn't know which version of flatMap() to use.

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

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

In this case you have to call reverse() on indices first so that they're enumerated in reverse order. Otherwise by the time you get to the end of the array you'll be attempting to remove an index that doesn't exist anymore.

1 Comment

Note, remove at index is really expensive when removing throughout the whole array like this.
1

Swift 4.2

A function accepting generics and producing reduced result

func stripElements<T>(in array:[T]) -> [T] {
    return array.enumerated().filter { (arg0) -> Bool in
        let (offset, _) = arg0
        return offset % 2 != 0
        }.map { $0.element }
}

Comments

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.