在Swift 3中从数组中删除特定对象 [英] Remove specific object from array in swift 3

查看:316
本文介绍了在Swift 3中从数组中删除特定对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Swift 3中尝试从数组中删除特定对象时遇到问题.我想从屏幕快照中删除数组中的项,但我不知道解决方案.

I have a problem trying to remove a specific object from an array in Swift 3. I want to remove item from an array as in the screenshot but I don't know the solution.

如果您有任何解决方案,请与我分享.

If you have any solutions please share with me.

推荐答案

简短回答

您可以在数组中找到对象的索引,然后使用索引将其删除.

you can find the index of object in array then remove it with index.

var array = [1, 2, 3, 4, 5, 6, 7]
var itemToRemove = 4
if let index = array.index(of: itemToRemove) {
    array.remove(at: index)
}

长期回答

如果您的数组元素确认为可哈希协议,则可以使用

if your array elements confirm to Hashable protocol you can use

array.index(of: itemToRemove)

因为Swift可以通过检查数组元素的hashValue找到索引.

because Swift can find the index by checking hashValue of array elements.

但是,如果您的元素未确认为Hashable协议,或者您不想基于hashValue查找索引,则应告诉 index 方法如何找到该项目.所以您使用index(where:)代替,它要求您提供谓词clouser来查找正确的元素

but if your elements doesn't confirm to Hashable protocol or you don't want find index base on hashValue then you should tell index method how to find the item. so you use index(where: ) instead which asks you to give a predicate clouser to find right element

// just a struct which doesn't confirm to Hashable
struct Item {
    let value: Int
}

// item that needs to be removed from array
let itemToRemove = Item(value: 4)

// finding index using index(where:) method
if let index = array.index(where: { $0.value == itemToRemove.value }) {

    // removing item
    array.remove(at: index)
}

如果您在很多地方都使用index(where :)方法,则可以定义一个谓词函数并将其传递给index(where:)

if you are using index(where:) method in lots of places you can define a predicate function and pass it to index(where:)

// predicate function for items
func itemPredicate(item: Item) -> Bool {
    return item.value == itemToRemove.value
}

if let index = array.index(where: itemPredicate) {
    array.remove(at: index)
}

有关更多信息,请阅读Apple的开发人员文档:

for more info please read Apple's developer documents:

索引(其中:)

索引(of :)

这篇关于在Swift 3中从数组中删除特定对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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