如何在Swift中删除数组中的每个其他元素?

时间:2021-08-31 00:34:57

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)?

现在,如何删除“a”,“c”,“e”,“g”和“i”(数组中的所有偶数索引)?

Thanks!

3 个解决方案

#1


12  

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:

您可以使用步幅完成此操作,而不是使用C风格的for循环(在即将推出的Swift版本中将其弃用)。

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] }

#2


6  

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

enumerate接受一个元素数组并返回一个元组数组,其中每个元组是一个索引数组对(例如(.0 3,.1“d”))。然后,我们使用模运算符删除奇数元素。最后,我们使用map将元组数组转换回普通数组。 HTH

#3


2  

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

有很多不同的方法来实现这一目标,但这里有一些我觉得有趣的方法:

Using flatMap() on indices:

在索引上使用flatMap():

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.

注意:结果需要定义为[String],否则编译器不知道要使用哪个版本的flatMap()。

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.

在这种情况下,您必须首先对索引调用reverse(),以便它们以相反的顺序枚举。否则,当您到达数组末尾时,您将尝试删除不再存在的索引。

#1


12  

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:

您可以使用步幅完成此操作,而不是使用C风格的for循环(在即将推出的Swift版本中将其弃用)。

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] }

#2


6  

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

enumerate接受一个元素数组并返回一个元组数组,其中每个元组是一个索引数组对(例如(.0 3,.1“d”))。然后,我们使用模运算符删除奇数元素。最后,我们使用map将元组数组转换回普通数组。 HTH

#3


2  

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

有很多不同的方法来实现这一目标,但这里有一些我觉得有趣的方法:

Using flatMap() on indices:

在索引上使用flatMap():

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.

注意:结果需要定义为[String],否则编译器不知道要使用哪个版本的flatMap()。

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.

在这种情况下,您必须首先对索引调用reverse(),以便它们以相反的顺序枚举。否则,当您到达数组末尾时,您将尝试删除不再存在的索引。