删除Swift数组中最后一次出现的元素 [英] Remove the last occurrence of an element in a Swift array

查看:409
本文介绍了删除Swift数组中最后一次出现的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要删除[Bool]数组中特定元素的最后一次出现.例如,在JavaScript中,将是:

I need to remove the last occurrence of a specific element in a [Bool] Array. For example in JavaScript this would be:

var k = [true, true, false];
k.splice(k.lastIndexOf(true), 1);
==> [true, false]

我将如何在Swift中实现相同的行为?

How would I achieve the same behavior in Swift?

推荐答案

通过反向枚举,您可以轻松找到值的最后一次出现.找到所需的值后,只需将其删除并退出循环即可.使用reverse()以相反的顺序枚举索引范围:

You can easily find the last occurrence of a value by enumerating in reverse. When you find the value you're looking for, just remove it and break from the loop. Use reverse() enumerate the range of indexes in reverse order:

for i in array.indices.reversed() where array[i] == searchValue {
    array.remove(at: i)
    break
}

这篇关于删除Swift数组中最后一次出现的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆