【问题标题】:how to get the index value in dictionary using swift如何使用swift获取字典中的索引值
【发布时间】:2018-12-10 10:47:22
【问题描述】:

由于我是 swift 编程语言的新手。我正在使用两个项目的字典,现在我需要获取特定字典值的索引路径。我正在使用以下代码

var dictionaryitems = ["computer":"something to make work easy","pen":"used for writing something"]
print(dictionaryitems["pen"])

【问题讨论】:

  • 你能解释一下,为什么你需要 indexPath ???如果您使用的是 tableView,则使用数组而不是字典。
  • 不,我没有使用表格视图。我需要索引路径进行其他计算
  • 字典根据定义是无序的。它基于 key 而不是基于 index

标签: swift swift3 swift2


【解决方案1】:

为此使用 firstIndex

 let index = dictionaryitems.firstIndex(where: {$0.key == "pen"})

【讨论】:

  • 我收到以下错误“'[String : String]' 类型的值没有成员 'firstIndex'”
  • 抱歉,好像只有最新版的swift才有这个功能
【解决方案2】:

您可以通过

获取键或值的索引
let index = Array(Dictionary.keys).index(of: key/value)

这样你会得到一个可选值,你可以使用 if-let 或 guard 语句解包以供进一步使用

【讨论】:

    【解决方案3】:
    var dictionaryitems = ["computer":"something to make work easy","pen":"used for writing something"]
    
    if let index = dictionaryitems.index(forKey: "pen")  {
        print(dictionaryitems[index].key, ":", dictionaryitems[index].value)
    }
    

    【讨论】:

      【解决方案4】:

      这是一个如何使用 swift 获取字典索引的示例 >

      if let index = carDataArray?.index(where: {$0["carName"] as! String == "BMW"}) {
                  print("Car Found")
              }
      

      【讨论】:

        猜你喜欢
        • 2018-11-13
        • 2013-01-10
        • 2016-08-31
        • 2019-01-29
        • 1970-01-01
        • 2022-12-17
        • 2017-10-31
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多