【问题标题】:How to get the value for 'keys in an array' in Dictionary in swift4如何在swift4中的字典中获取“数组中的键”的值
【发布时间】:2018-10-04 02:45:42
【问题描述】:

我做了一本字典。

let fruits = ["aa":"apple", "bb":"banana", "gg":"grapes" ]

我有一个数组,其中包含相同的“水果”键

let fruitsKeys = ["aa", "bb", "gg"]

我想通过使用数组“fruitsKey”中的元素一一检查字典“水果”来获取“水果”值数组。

这个数组看起来像

fruitsValue = ["apple", "banana", "grapes"]

如何在字典中获取“数组中的键”的值?

【问题讨论】:

  • 我已经读了好几遍了,但我不知道你到底想在这里做什么。你能澄清一下吗?显示更多代码。展示您迄今为止所做的尝试,并清楚地说明您需要帮助的地方。
  • let fruitsValue = Array(fruits.values)
  • @rmaddy 我只想从数组“fruits”中获取基于数组“fruitsKeys”中可用键的值。我想制作具有已获取值的数组。
  • fruitKeys 数组中的键是否只是fruits 中的一些键,还是总是所有键?
  • @rmaddy 一些键!

标签: swift dictionary key


【解决方案1】:

要获取键值数组对应值的数组,使用compactMap创建数组:

let fruits = ["aa":"apple", "bb":"banana", "gg":"grapes" ]

let fruitsKeys = ["aa", "bb", "gg"]

let fruitsValue = fruitsKeys.compactMap { fruits[$0] }

print(fruitsValue)
["apple", "banana", "grapes"]

注意事项:

  1. 相应的值将与原始数组中的键的顺序相同。
  2. 如果键实际上没有值,这将安全地跳过该键,因为查找将返回 nilcompactMap 将忽略它。

【讨论】:

    【解决方案2】:

    在这种情况下,如果您只需要所有水果值,则无需通过迭代 fruitsKeys 进行搜索。只需像这样遍历所有值:

    for fruit in fruits {
        fruitsValue.append(fruit.value)
    }
    

    如果您需要根据fruitsKeys 中的可用键获取值,则迭代可能是这样的:

    for fruit in fruits {
        if fruitsKeys.contains(fruit.key) {
            fruitsValue.append(fruit.value)
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-07-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-16
      • 2014-12-31
      • 2021-12-06
      相关资源
      最近更新 更多