从swift 3

时间:2016-12-21 05:08:17

标签: arrays swift3

Remove Object From Array Swift 3

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

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

3 个答案:

答案 0 :(得分:29)

简答

你可以在数组中找到对象的索引,然后用索引删除它。

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

长答案

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

array.index(of: itemToRemove)

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

但是如果你的元素没有确认Hashable协议,或者你不想在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)
}
  

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

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

答案 1 :(得分:16)

根据您的代码,改进可能是这样的:

    if let index = arrPickerData.index(where: { $0.tag == pickerViewTag }) {
        arrPickerData.remove(at: index)
        //continue do: arrPickerData.append(...)
    }

索引现有意味着Array包含具有该Tag的对象。

答案 2 :(得分:4)

我使用了此处提供的解决方案:Remove Specific Array Element, Equal to String - Swift Ask Question

这是其中一个解决方案(如果对象是字符串):

myArrayOfStrings = ["Hello","Playground","World"]
myArrayOfStrings = myArrayOfStrings.filter{$0 != "Hello"}
print(myArrayOfStrings)   // "[Playground, World]"
相关问题