我在尝试从 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 的开发者文档:
关于arrays - 在 swift 3 中从数组中删除特定对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41255494/