Swift字典在没有访问权限或知道密钥的情况下获取值

时间:2017-05-09 07:03:56

标签: swift dictionary

我正在使用字典并尝试在不知道或访问密钥的情况下获取值。 这是我的字典看起来像"Olivia":[2.0, 0.0, 1.0, 3.0],"Amber":[60.0, 0.0, 0.0, 1.0]这是一个[String: ArrayDouble]字典,但我想检查Value(ArrayDouble)中是否有包含60.0的值,然后显示该值的Key。我试图做的是:

let number = 60.0
for (key, value) in dict{

  if (number== value[0]){

    print(...the key)

  }else{

}

2 个答案:

答案 0 :(得分:2)

您还可以使用优先(_ where :)

let item = dict.first { key, value in
  value.contains(60)
}

let key = item?.key // this is your key Amber

有了这个,您可以创建一个谓词函数,您可以根据需要进行修改,

let predicate = { (num: Double) -> Bool in
  num == 60.0
}

let dict = ["Olivia":[2.0, 0.0, 1.0, 3.0],"Amber":[60.0, 0.0, 0.0, 1.0]]

let item = dict.first { key, value in
  value.contains(where: predicate)
}

item?.key

您可以根据需要更改谓词,

let predicate = {(num: Double) -> Bool in num > 60.0} // predicate to filter first key with values greater than 60.0

let predicate = {(num: Double) -> Bool in num < 60.0} // predicate to filter first key with values greater than 60.0

等等。

答案 1 :(得分:1)

你可以这样。

let dic = ["Olivia":[2.0, 0.0, 1.0, 3.0],"Amber":[60.0, 0.0, 0.0, 1.0]]
let filterKeys = dic.flatMap { $0.value.first == 60 ? $0.key : nil } 
//If you are having only one pair like that then simply access the first object from array
print(filterKeys.first)
//Other wise you can access the whole array
print(filterKeys)

注意:如果您想检查ArrayDouble是否包含特定值而不是仅仅比较第一个元素,您可以尝试这样做。

let filterKeys = dic.flatMap { $0.value.contains(60) ? $0.key : nil } 
//If you are having only one pair like that then simply access the first object from array
print(filterKeys.first)
//Other wise you can access the whole array
print(filterKeys)

编辑:如果您想检查包含> 60的对象的数组,可以使用contains(where:)

let filterKeys = dic.flatMap { $0.value.contains(where: { $0 > 60}) ? $0.key : nil }