【问题标题】:How to get the index of a specific object in Dictionary in swift如何快速获取字典中特定对象的索引
【发布时间】:2016-11-24 17:34:09
【问题描述】:

我正在以这种方式在Dictionary Array 中搜索一个键的值。

if let result = self.lasrIDArray.flatMap({$0["\(self.selectedTitle)"]}).first  {
            print("-------RESULT------\(result)") //->title of the other
}

但是我想做的是获取这个 result 包含对象的索引。

我该怎么做?

【问题讨论】:

标签: arrays swift dictionary flatmap


【解决方案1】:

你可以枚举数组:

if let indexAndResultTuple = (self.lasrIDArray.enumerate().filter{$0.element["\(self.selectedTitle)"] != nil}).first {
    let index = indexAndResultTuple.0
    let result = indexAndResultTuple.1["\(self.selectedTitle)"]!

    print("-------RESULT------\(result) --atIndex--\(index)") //->title of the other
}

【讨论】:

  • @dfri 如果我理解问题,有字典数组,我们需要包含键值“(self.selectedTitle)”的第一个字典的索引
  • 仔细看看这个描述得很少的问题,我相信你是对的,我的错!
  • 感谢您的回答。你能告诉我 $0.index 处的索引是什么
  • 我在 $0.index 的逗号附近遇到语法错误,它要求我添加 ;
  • @Irrd 看起来像语法错误。检查我的答案编辑更改
【解决方案2】:

试试

对于 self.lasrIDArray 中的项目 {

如果 self.lasrIDArray.containsObject(item.valueForKey("yourKey")!){

//你的逻辑在这里

} }

【讨论】:

  • 它是一个字典对象数组。同一个键可以重复
猜你喜欢
  • 2019-09-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-05-14
  • 2017-04-08
  • 1970-01-01
相关资源
最近更新 更多