从swift 3中的数组中删除特定对象

Soc*_*eat 19 arrays swift3

从数组Swift 3中删除对象

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

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

Moh*_*ijf 30

简答

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

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

答案很长

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

array.index(of: itemToRemove)
Run Code Online (Sandbox Code Playgroud)

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

但是如果你的元素没有确认Hashable协议或你不希望找到基于hashValue的索引,那么你应该告诉索引方法如何找到该项.所以你使用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)
}
Run Code Online (Sandbox Code Playgroud)

如果你在很多地方使用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)
}
Run Code Online (Sandbox Code Playgroud)

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

指数(其中:)

指数:)


Yun*_*HEN 17

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

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

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

  • 是的,我也这么认为兄弟。 (2认同)

nyx*_*xee 6

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

这是那里的解决方案之一(如果对象是字符串):

myArrayOfStrings = ["Hello","Playground","World"]
myArrayOfStrings = myArrayOfStrings.filter{$0 != "Hello"}
print(myArrayOfStrings)   // "[Playground, World]"
Run Code Online (Sandbox Code Playgroud)