【问题标题】:How can I get key's value from dictionary in Swift?如何从 Swift 中的字典中获取键的值?
【发布时间】:2014-11-02 16:01:29
【问题描述】:

我有一本 Swift 字典。我想得到我的钥匙的价值。关键方法的对象对我不起作用。如何获取字典键的值?

这是我的字典:

var companies = ["AAPL" : "Apple Inc", "GOOG" : "Google Inc", "AMZN" : "Amazon.com, Inc", "FB" : "Facebook Inc"]

for name in companies.keys { 
    print(companies.objectForKey("AAPL"))
}

【问题讨论】:

标签: dictionary swift key-value


【解决方案1】:

为了找到下面的价值使用

if let a = companies["AAPL"] {
   // a is the value
}

用于遍历字典

for (key, value) in companies {
    print(key,"---", value)
}

最后要按值搜索,首先添加扩展名

extension Dictionary where Value: Equatable {
    func findKey(forValue val: Value) -> Key? {
        return first(where: { $1 == val })?.key
    }
}

然后打电话

companies.findKey(val : "Apple Inc")

【讨论】:

    【解决方案2】:

    来自 Apple 文档

    您可以使用下标语法从字典中检索特定键的值。因为可以请求不存在值的键,所以字典的下标返回字典值类型的可选值。如果字典包含请求键的值,则下标返回一个可选值,其中包含该键的现有值。否则,下标返回 nil:

    https://developer.apple.com/documentation/swift/dictionary

    if let airportName = airports["DUB"] {
        print("The name of the airport is \(airportName).")
    } else {
        print("That airport is not in the airports dictionary.")
    }
    // prints "The name of the airport is Dublin Airport."
    

    【讨论】:

      【解决方案3】:

      使用下标来访问字典键的值。这将返回一个可选的:

      let apple: String? = companies["AAPL"]
      

      或

      if let apple = companies["AAPL"] {
          // ...
      }
      

      您还可以枚举所有键和值:

      var companies = ["AAPL" : "Apple Inc", "GOOG" : "Google Inc", "AMZN" : "Amazon.com, Inc", "FB" : "Facebook Inc"]
      
      for (key, value) in companies {
          print("\(key) -> \(value)")
      }
      

      或枚举所有值:

      for value in Array(companies.values) {
          print("\(value)")
      }
      

      【讨论】:

        猜你喜欢
        • 2016-07-22
        • 2018-03-24
        • 1970-01-01
        • 2022-12-17
        • 1970-01-01
        • 2016-05-07
        • 1970-01-01
        • 2019-02-04
        • 1970-01-01
        相关资源
        最近更新 更多