【问题标题】:Remove specific object from array in swift 3在swift 3中从数组中删除特定对象
【发布时间】:2016-12-21 05:08:16
【问题描述】:

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

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

【问题讨论】:

  • 请在您的问题中发布实际代码,而不是图片。
  • 您需要指定对象所在的索引。
  • 请阅读Array 的文档。它显示了在数组中添加和删除对象的示例。

标签: arrays swift3


【解决方案1】:

简答

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

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

【讨论】:

  • 为什么要打扰array.contains?只需获取索引即可。
  • 只是为了确定 :D 但是是的,您可以删除 array.contains 并使用 if let index = array.index(of : itemToRemove)
  • @Mohammadalijf 你不需要array.contains(itemToRemove) 只需if let index = array.index(of: itemToRemove) 就足够了
  • @Socheat 它就在 Swift Array 类的文档中。 index(of:).
【解决方案2】:

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

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

索引存在意味着数组包含带有该标签的对象。

【讨论】:

  • @Socheat,???,越用 Swift 越觉得它强大!
  • 是的,我想是的,兄弟。
【解决方案3】:

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

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

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

【讨论】:

    猜你喜欢
    • 2017-04-13
    • 2019-02-03
    • 1970-01-01
    • 1970-01-01
    • 2018-10-03
    • 2018-01-13
    • 2019-11-02
    • 1970-01-01
    • 2018-07-11
    相关资源
    最近更新 更多