删除Swift数组中最后一个元素

时间:2015-08-12 00:15:52

标签: arrays swift indexing boolean

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

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

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

3 个答案:

答案 0 :(得分:7)

您可以通过反向枚举轻松找到最后一次出现的值。当您找到要查找的值时,只需将其删除并从循环中断开即可。使用reverse()以相反的顺序枚举索引范围:

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

答案 1 :(得分:5)

Xcode 8.2•Swift 3.0.2

var k = [true, true, true, false, true, false]

if let index = k.reversed().index(of: true) {
    k.remove(at: index.base - 1)
}

print(k)   // "[true, true, true, false, false]"

如果您想创建一个扩展以将此功能添加到Array,您需要将其约束为等值元素:

extension Array where Element: Equatable {
    ///  Returns the last index where the specified value appears in the collection.
    ///  After using lastIndex(of:) to find the last position of a particular element in a collection, you can use it to access the element by subscripting.
    /// - Parameter element: The element to find the last Index
    func lastIndex(of element: Element) -> Index? {
        if let index = reversed().index(of: element) {
            return  index.base - 1
        }
        return nil
    }
    /// Removes the last occurrence where the specified value appears in the collection.
    /// - Returns: True if the last occurrence element was found and removed or false if not.
    /// - Parameter element: The element to remove the last occurrence.
    @discardableResult
    mutating func removeLastOccurrence(of element: Element) -> Bool {
        if let index = lastIndex(of: element) {
            remove(at: index)
            return true
        }
        return false
    }
}

游乐场测试

var k = [true, true, true, false, true, false]

k.removeLastOccurrence(of: true)
print(k)                        // "[true, true, true, false, false]"

答案 2 :(得分:2)

我认为没有像lastIndexOf那样的内置函数,所以它的工作量更多。

var removeIndex: Int?

for (index, item) in enumerate(arr) {
    if item == search {
        removeIndex = index 
    }
}

if let removeIndex = removeIndex {
    arr.removeAtIndex(removeIndex)
}

arr是您要搜索的数组(示例中为k),search是您要搜索的内容(示例中为true)。