【问题标题】:How to find index of Array which the array contains dictionaries in swift 3?如何在swift 3中找到数组包含字典的数组索引?
【发布时间】:2016-11-24 12:31:04
【问题描述】:

如果我像这样定义数组意味着

var tempArray = [String]()
tempArray = ["Hai", "Hello", "How are you?"]
let indx = tempArray.index(of:"Hai")

有一个选择

索引(的:)

查找索引,但如果我这样定义意味着

var tempArray = [AnyObject]() 
//or 
var tempArray = [[String:AnyObject]]()() 

没有找到索引

的选项

【问题讨论】:

  • 您如何在字典中查找对象,您是否期望具有某些特定键的对象?

标签: ios arrays swift3


【解决方案1】:

在 Swift.swift 中你可以看到这个声明:

extension Collection where Iterator.Element : Equatable {
    public func index(of element: Self.Iterator.Element) -> Self.Index?
}

此方法仅适用于具有 Equatable 元素的数组; AnyObject 不符合 Equatable

已编辑:

不过,您可以像这样查找您的元素:

    var tempArray = [AnyObject]()
    for item in tempArray {
       if let typedItem = item as? SomeYourType {
          if typedItem == searchItem {

          }
       }
    }

已编辑:

要删除,您可以使用这样的东西(未测试):

someArr.filter({object in guard let typedObject = (object as? YourType) else {return true}; return typedObject != yourObject })

【讨论】:

  • 实际上,我想从数组中删除特定对象。在没有找到索引的情况下,如何从数组中删除该对象?
猜你喜欢
  • 2017-02-09
  • 1970-01-01
  • 2020-09-27
  • 2018-01-05
  • 1970-01-01
  • 1970-01-01
  • 2014-08-13
  • 2018-05-24
  • 1970-01-01
相关资源
最近更新 更多