arrays - 在 swift 3 中从数组中删除特定对象

标签 arrays swift3

Remove Object From Array Swift 3

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

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

最佳答案

简答

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

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

长答案

如果您的数组元素符合 Hashable 协议(protocol),您可以使用

array.index(of: itemToRemove)

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

但是如果您的元素不符合 Hashable 协议(protocol)或者您不想基于 hashValue 查找索引,那么您应该告诉 index 方法如何查找该项目。所以你使用index(where:)代替它要求你给出一个谓词clouser来找到正确的元素

// 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)
}

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 的开发者文档:

index(where:)

index(of:)

关于arrays - 在 swift 3 中从数组中删除特定对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41255494/

相关文章:

java - 按路径将 zip 文件夹中的文件放入字符串数组中

javascript - 数组比较并获取计数

ios - CoreData 不会为 Swift 3 生成 NSManagedObject

Swift - 有人能帮我理解 .sorted(by :) works in this example?

php - 如果你有菜单数组,如何设置 wordpress 菜单

php - 无法在 PHP 中比较 2 个数组(不区分大小写)

java - 为什么 Java 中不能通过引用调整数组大小?

ios - 从 nib UIView 加载未使用的 Swift 3

ios - "Expression was too complex to be solved in reasonable time"在 swift 3 中向字典添加数据时,在 swift 2.3 中工作正常

swift - 以编程方式添加约束会导致崩溃